This question already has answers here:
What is the performance of the Last() extension method for List<T>?
(5 answers)
Closed 5 years ago.
How effective is using Last() for arrays?
var array = new[] { ... };
var last = array.Last(); // or array[array.Length - 1]
In sources it only distinguish IList<T>, so is that true what Last() will enumerate a complete array to return last item? Funny stuff is msdn example without a single note.
Array does implement IList<T>:
var array = new int[] { 1, 2, 3 };
var list = (IList<int>)array;
So Last will not enumerate all array but instead will do array[array.Length - 1] (with a check that array is not empty of course - it which case it will throw).
Related
This question already has answers here:
Intersect two arrays
(2 answers)
Closed 5 months ago.
I've got 2 arrays of Int, and I want to keep only elements from second array that contains the first array elements.
int [] first = new int[2] { 1, 2};
int [] second = new int[5] { 99, 1, 2, 97, 95};
I have tried something like below.
foreach(int x in first){
second.Where(s=>s==x);
}
But it doesn't help me because I need to compare both elements from first array
second.Where(s=>s==x[0] && s[1])
and if the int is bigger I need. Do you have any ideas how to get below code line?
second.Where(s=>s==x[0] && s== x[1] && ... && s==x[n])
var elements = second.Where(first.Contains);
Maybe materialize it with a .ToList() or ToArray() call.
If the first list is really large, you could think about a faster version than the .Contains method, but for your lists, it would be overkill.
var firstSet = first.ToHashSet();
var result = second.Where(x => firstSet.Contains(x)).ToArray();
This question already has answers here:
Convert 2 dimensional array
(4 answers)
Closed 7 years ago.
Is there an elegant way to flatten a 2D array in C# (using Linq or not)?
E.g. suppose
var my2dArray = new int[][] {
new int[] {1,2,3},
new int[] {4,5,6}
};
I want to call something like
my2dArray.flatten()
which would yield
{1,2,3,4,5,6}
Any ideas?
You can use SelectMany
var flat = my2dArray.SelectMany(a => a).ToArray();
This will work with a jagged array like in your example, but not with a 2D array like
var my2dArray = new [,] { { 1, 2, 3 }, { 1, 2, 3 } };
But in that case you can iterate the values like this
foreach(var item in my2dArray)
Console.WriteLine(item);
This question already has answers here:
Fill List<int> with default values? [duplicate]
(5 answers)
Closed 3 years ago.
I'm looking for the equivalent of Array.Fill but for List
Is it possible to fill all list items with certain value
Array.Fill(counters, max); // this works
listName.Fill(5); //something like this
would fill a list with 5's
I don't want to use a loop
Given that the list have some items
Enumerable.Repeat(TResult, Int32) Method
var fives = Enumerable.Repeat(5, 10).ToList(); // create list with ten fives
You need to loop all items for existing list anyway, just wrap the loop with an extension method.
public static void FillWith<T>(this List<T> list, T value)
{
for (var i = 0, i < list.Count, i++)
{
list[i] = value;
}
}
Usage
var list = new List<int> { 1, 2, 3, 4, 5 };
list.FillWith(42);
var output string.Join(",", list); // 42,42,42,42,42
This question already has answers here:
Array Size (Length) in C#
(9 answers)
Closed 8 years ago.
I had a quick question on comparing the amount of entries in an array to a int. For example,
TO CLEAR UP ANY CONFUSION I WANT TO KNOW HOW MANY WORDS THERE ARE IN THE ARRAY NOT CHARACTERS
int i = 0;
string[] array = {"bob", "john"};
if(i == int.Parse(array))
{
//int i should equal 2 for this if statement to be true
}
SO that was just an example so you get the idea here's the real code.
if(i == int.Parse(split))
{
MessageBox.Show("Teams are successfully made");
break;
}
You can use the Length propery of the array as:
if(i == array.Length)
You can use the Array.Length property:
if (i == array.Length)
{
MessageBox.Show("Teams are successfully made");
break;
}
The Length property is a 1 based number. That means if your array has 3 items in it, Length will be 3, however if you want to reference the third item in the array, you will have to use an index of 2 because the reference is 0 based. See the following example:
string[] someArray = { "arrays", "are", "amazing" };
Console.WriteLine(someArray.Length); // Prints 3
Console.WriteLine(someArray[2]); // Prints "amazing"
Console.WriteLine(someArray[someArray.Length]); // Blows up because there is no
// element of the array with
// index of 3.
Console.WriteLine(someArray[someArray.Length - 1]); // Prints "amazing"
This question already has answers here:
Using Linq to get the last N elements of a collection?
(20 answers)
how to take all array elements except last element in C#
(6 answers)
Closed 8 years ago.
I have a string array in c#.Now as per my requirement i have to get the last ,second last and one element before second last elements in string but i am not getting how to get it.
Here is my string array.With Last() i am able to get the last element but second last and before second last i am not getting to find out.
string[] arrstr = str.Split(' ');
With .Last() i am able to get the last element but rest of the elements i am not able to get.
Please help me..
Use:
string[] arrstr = str.Reverse().Take(3).Reverse().ToArray();
In more recent versions of c# you can now use:
string[] arrstr = str.TakeLast(3).ToArray();
var threeLastElments = arrstr.Reverse().Take(3).Reverse().ToArray();
It actually gets the number of elements and skip the remaining element from the total count and take the specified amount
you can replace the 3 with N and use as method
string[] res = arrstr.Skip(Math.Max(0, arrstr.Count() - 3)).Take(3).ToArray();
Get a substring:string arrstr = str.Substring(str.Length - 4, 3);
More on C# strings
Why don't you calculate the length using obj.length; and then use arr[i] inside the loop and start the loop from last value.
To offer another solution, one which will be much more performant than LINQ queries ...
public static string[] getLast3(string[] src)
{
if (src.Length <= 3)
return src;
var res = new string[3];
Array.Copy(src, src.Length - 3, res, 0, 3);
return res;
}