What would be the equivalent for these code samples in LINQ (C#):
int[] items = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int number = -1;
foreach (int i in items)
{
if (i == 5)
{
number = i;
break;
}
}
And how would you replace a for loop with two (or more) conditions in LINQ?
(it is similar to the code above, couldn’t come up with a better example. Imagine that other conditions or checks happen there in the for loop)
int[] items = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int number = -1;
for (int i = 0; i < items.Length && number == -1; i++)
{
if (items[i] == 5)
number = items[i];
}
And the third piece of code, how would this be translated in LINQ:
List<int> items2 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int i = items2.Count - 1;
for (; i > 0; i--)
items2.RemoveAt(i);
Thanks in advance.
The first two are pretty odd, but basically they’re effectively:
or
An alternative way of doing this:
If you can come up with more realistic operations, we can come up with more sensible LINQ queries 🙂
The third snippet can’t really be translated into LINQ as it’s not a query – it’s mutating the list.