LINQ/C#: Where & Foreach using index in a list/array

26,247

Solution 1

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 })

Solution 2

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");

Solution 3

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

Share:
26,247
Andrew White
Author by

Andrew White

Programming for kicks

Updated on July 05, 2022

Comments

  • Andrew White
    Andrew White almost 2 years

    I have a list/array and need to process certain elements, but also 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?