LINQ/C#: Where & Foreach using index in a list/array
I have a list/array and need to process certain elements, but a开发者_JS百科lso need the index of the element in the processing. Example:
List Names = john, mary, john, bob, simon Names.Where(s => s != "mary").Foreach(MyObject.setInfo(s.index, "blah")
But cannot use the "index" property with lists, inversely if the names were in an Array I cannot use Foreach... Any suggestions?
You should use a simple for
loop, like this:
var someNames = Names.Where(s => s != "mary").ToArray();
for (int i = 0; i < someNames.Length; i++)
someNames.setInfo(i, "blah");
LINQ is not the be-all and end-all of basic loops.
If you really want to use LINQ, you need to call Select
:
Names.Where(s => s != "mary").Select((s, i) => new { Index = i, Name = s })
Yes there is a way without using a loop.
You just need to .ToList()
your .Where()
clause
Names.Where(s => s != "mary").ToList().Foreach(MyObject.setInfo(s.index, "blah");
Foreach perform on each element from the collection. Ref: https://msdn.microsoft.com/en-us/library/bwabdf9z(v=vs.110).aspx
Below is the sample code for your case
List<string> Names = new List<string> { "john", "mary", "john", "bob", "simon" };
int index = 0;
Names.Where(s => s != "mary").ToList().ForEach(x => printItem(index++,x));
printItem method
public static void printItem(int index, string name){
Console.WriteLine("Index = {0}, Name is {1}",index,name);
}
Output:
Index = 0, Name is john
Index = 1, Name is john
Index = 2, Name is bob
Index = 3, Name is simon
精彩评论