C#: Replacing loops with LINQ
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:
int number = items.Contains(5) ? 5 : -1;
or
int number = items.Any(x => x == 5) ? 5 : -1;
An alternative way of doing this:
int number = items.Where(x => x == 5).DefaultIfEmpty(-1).First();
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.
As Jon points out, the last one can't be translated to LINQ. However, it can be simplified as:
var survivers = 1;
items2.RemoveRange(survivers , items2.Count - survivers);
精彩评论