I have an int array, it’s a concatenated array from multiple similar arrays all starting at 1.
1, 2, 3, 4
1, 2
1, 2, 3
1, 2
int[] list = { 1, 2, 3, 4, 1, 2, 1, 2, 3, 1, 2 };
What I am trying to achieve is to get the “last set” of the result which is {1, 2}.
Attempt:
int[] list = { 1, 2, 3, 4, 1, 2, 1, 2, 3, 1, 2 };
List<int> lastSet = new List<int>();
var totalSets = list.Count(x => x == 1);
int encounter = 0;
foreach (var i in list)
{
if (i == 1)
encounter += 1;
if (encounter == totalSets)
lastSet.Add(i);
}
lastSet.ToList().ForEach(x => Console.WriteLine(x));
Is there a better way to achieve this using LINQ, perhaps SkipWhile, GroupBy, Aggregate?
If you can either make your list be an actual
List<int>or if it doesn’t bother you to create a copy of the list via.ToList(), you can do this:Otherwise,
Aggregatecan work, but it’s a little ugly:Update
As dtb points out, you can use Array.LastIndexOf rather than creating a List: