I want to create a new array. Let's say
int[] clickNum = new int[800];
Then I want to do something like clickNum = 2, which would make all array elements starting from clickNum[0] to clickNum[800], set to 2. I know there's a way to do it by using a loop; but what I am after is just a function or a method to do it.
I suppose you could use Enumerable.Repeat when you initialise the array:
int[] clickNum = Enumerable.Repeat(2, 800).ToArray();
It will of course be slower, but unless you're going to be initiating literally millions of elements, it'll be fine.
A quick benchmark on my machine showed that initialising 1,000,000 elements using a for loop took 2ms, but using Enumerable.Repeat took 9ms.
This page suggests it could be up to 20x slower.
I don't think there's any built-in function to fill an existing array/list.
You could write a simple helper method for that if you need the operation in several places:
static void Fill<T>(IList<T> arrayOrList, T value)
{
for (int i = arrayOrList.Count - 1; i >= 0; i--)
{
arrayOrList[i] = value;
}
}
I guess you are looking for a function you created but you do not have the time to type it. So if you want it in a single line, try:
for(int i = 0; i < clickNum.Length; i++, clickNum[i] = 2);
Using Array.ConvertAll should be more efficient if you are working with very large arrays and performance is a concern:
int[] clickNum = Array.ConvertAll(new int[800], x => x = 2);
And you can also use a standard LINQ Select if performance doesn't worry you:
int[] clickNum = new int[800].Select(x => x = 2).ToArray();
Related
I'm learning c#, with my primary language before now being php. I was wondering how (or if) you could create an empty array in c#.
In php, you can create an array, and then add any number of entries to it.
$multiples=array();
$multiples[] = 1;
$multiples[] = 2;
$multiples[] = 3;
In c#, I'm having trouble doing something similar:
int[] arraynums = new int[];
arraynums[] = 1;
arraynums[] = 2;
arraynums[] = 3;
Which gives the error "array creation must have array size or array initializer." If I don't know how many entries I want to make, how do I do this? Is there a way around this?
If you don't know the size in advance, use a List<T> instead of an array. An array, in C#, is a fixed size, and you must specify the size when creating it.
var arrayNums = new List<int>();
arrayNums.Add(1);
arrayNums.Add(2);
Once you've added items, you can extract them by index, just like you would with an array:
int secondNumber = arrayNums[1];
c# arrays have a static size.
int[] arraynums = new int[3];
or
int[] arraynums = {1, 2, 3}
if you want to use dynamic sized array, you should use ArrayList, or List.
I would recommend using a different collection such as a List<T> or a Dictionary<TKey, TValue>. Calling the collection in PHP an array is just a misnomer. An array is a continuous fixed size block of memory that contains only a single type and offers direct access by calculating the offset for a given index. The data type in PHP does none of these things.
Examples;
List<int> my_ints = new List<int>();
my_ints.Add(500);
Dictionary<string, int> ids = new Dictionary<string, int>();
ids.Add("Evan", 1);
int evansId = ids["Evan"];
Examples of when to use an array;
string[] lines = File.ReadAllLines(myPath);
for (int i = 0; i < lines.Length; i++)
// i perform better than other collections here!
Newer way, since .NET 4.6 / Core 1.0, in case somebody hits this:
System.Array.Empty<T>() method.
This is more efficient if called multiple times, as it's backed by a single static readonly array generated at compile time.
https://learn.microsoft.com/en-us/dotnet/api/system.array.empty
https://referencesource.microsoft.com/#mscorlib/system/array.cs,3079
Try this post: Dynamic array in C#. It has a couple of links in the first answer that show alternate ways of indexing data. In C#, there is no way of making dynamic arrays but those links show some workarounds.
What I am trying to achieve is to add one item to a List, multiple times without using a loop.
I am going to add 50 numbers to a List and want all of those number to be equal to, let's say, 42. I am aware that I can simply create a small loop that runs 50 times and adds the same item over and over again, as such;
List<int> listFullOfInts = new List<int>();
int addThis = 42;
for(int i = 0; i < 50; i++)
listFullOfInts.Add(addThis);
What I am trying to do is something on the lines of;
listFullOfInts.AddRange(addThis, 50);
Or something that is similar to this at least, maybe using Linq? I have a vague memory of seeing how to do this but am unable to find it. Any ideas?
You can use Repeat:
List<int> listFullOfInts = Enumerable.Repeat(42, 50).ToList();
Demo
If you already have a list and you don't want to create a new one with ToList:
listFullOfInts.AddRange(Enumerable.Repeat(42, 50));
If you want to do add reference types without repeating the same reference, you can use Enumerable.Range+Select:
List<SomeClass> itemList = Enumerable.Range(0, 50)
.Select(i => new SomeClass())
.ToList();
You can't do it directly with LINQ since LINQ is side effect free but you can use some of what's found in the System.linq namespace to build the required.
public static void AddRepeated<T>(this List<T> self,T item, int count){
var temp = Enumerable.Repeat(item,count);
self.AddRange(temp);
}
you can then use that as you propose in your post
listFullOfInts.AddRepeated(addThis, 50);
Hello i have a problem with c# Arrays. I need a array to store some data in there...
My Code is that
double[] ATmittelMin;
ATmittelMin[zaehlMittel] = Gradient(x, xATmax, y, yATmax);
But the compiler says: not defined var
How can i define a double array without a fixed size ?
Thanks a lot!
Arrays are always fixed in size, and have to be defined like so:
double[] items1 = new double[10];
// This means array is double[3] and cannot be changed without redefining it.
double[] items2 = {1.23, 4.56, 7.89};
The List<T> class uses an array in the background and redefines it when it runs out of space:
List<double> items = new List<double>();
items.Add(1.23);
items.Add(4.56);
items.Add(7.89);
// This will give you a double[3] array with the items of the list.
double[] itemsArray = items.ToArray();
You can iterate through a List<T> just as you would an array:
foreach (double item in items)
{
Console.WriteLine(item);
}
// Note that the property is 'Count' rather than 'Length'
for (int i = 0; i < items.Count; i++)
{
Console.WriteLine(items[i]);
}
From what I see you did not declare the zaehlMittel variable. I guess this is what the compiler complains about.
Apart from that, even though you can of course determine the value of that variable programmatically, the moment you want to create an array its size must be known. This is the way arrays work.
In case you cannot do that easily, I suggest using some sort of dynamic datastructure, like a list or a set. Then, once all elements have been added, you are of course still free to create an array from that, as by that time you know the number of elements (even though there are convenience methods like toArray() that will even take care of that).
You have to instanciate the array before using it:
double[] ATmittelMin = new double[10];
ATmittelMin[zaehlMittel] = Gradient(x, xATmax, y, yATmax);
The obvious solution that springs to mind is to use a List:
List<double> ATmittelMin = new List<double>();
ATmittelMin.Add(Gradient(x, xATMax, y, yATMax);
But if you don't want to convert from a list to an array you can grow the array later:
double[] ATmittelMin = new double[10];
// Some code
int index = some_value;
if (index >= TmittelMin.Length)
{
Array.Resize(ATmittelMin, index+5); // So we're not constantly resizing the array
}
It's not ideal as you're doing a lot of the work that List is doing behind the scenes - probably a lot more efficiently than you can.
I'm looking for an ultra-easy way to generate a list of numbers, 1-200.
(it can be a List, Array, Enumerable... I don't really care about the specific type)
Apparently .Net 4.0 has a Sequence.Range(min,max) method.
But I'm currently on .Net 3.5.
Here is a sample usage, of what I'm after, shown with Sequence.Range.
public void ShowOutput(Sequence.Range(1,200));
For the moment, I need consequitive numbers 1-200. In future iterations, I may need arbitrary lists of numbers, so I'm trying to keep the design flexible.
Perhaps there is a good LINQ solution? Any other ideas?
.NET 3,5 has Range too. It's actually Enumerable.Range and returns IEnumerable<int>.
The page you linked to is very much out of date - it's talking about 3 as a "future version" and the Enumerable static class was called Sequence at one point prior to release.
If you wanted to implement it yourself in C# 2 or later, it's easy - here's one:
IEnumerable<int> Range(int count)
{
for (int n = 0; n < count; n++)
yield return n;
}
You can easily write other methods that further filter lists:
IEnumerable<int> Double(IEnumerable<int> source)
{
foreach (int n in source)
yield return n * 2;
}
But as you have 3.5, you can use the extension methods in System.Linq.Enumerable to do this:
var evens = Enumerable.Range(0, someLimit).Select(n => n * 2);
var r = Enumerable.Range( 1, 200 );
Check out System.Linq.Enumerable.Range.
Regarding the second part of your question, what do you mean by "arbitrary lists"? If you can define a function from an int to the new values, you can use the result of Range with other LINQ methods:
var squares = from i in Enumerable.Range(1, 200)
select i * i;
I need to get an array containing reversed alternate elements of the original array.
For example: an array containing elements {12,56,67}.
I need to get an array containing {67,12}
(reversing array to get {67,56,12} then take alternate elements means {67,12})
I need to do this in c#
This won't be the shortest answer you'll get, but it seems fairly optimised to me.
int[] rgIn = new int[]{0,1,2,3,4,5};
int[] rgOut = new int[rgIn.Length / 2];
int ixOut = 0;
for (int ixIn = rgIn.Length - 2; ixIn >= 0; ixIn -= 2)
{
rgOut[ixOut++] = rgIn[ixIn];
}
If you're using C# 3, try this:
int[] array = {1,2,3,4,5,6};
var x = array.Reverse().Where( (n,i) => i % 2 !=0);
Where is an extension method (new in C# 3.0) which forms part of a language feature called LINQ. It filters a sequence based on a predicate. In the sample above, n is the element of the sequence and i is the zero based index of the element in the sequence. Both are strongly typed. The predicate i%2!=0 is saying that the index of the element is not directly divisible by 2, so what we are saying is reverse the list and select the odd elements from it.
Not the most efficient solution, but short and concise.