3

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?

2
  • 2
    Do you want the index in the original collection or the index in the filtered set? Commented Jun 6, 2010 at 11:50
  • 1
    possible duplicate of C# foreach with index Commented Feb 9, 2012 at 22:45

3 Answers 3

7

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 })
Sign up to request clarification or add additional context in comments.

1 Comment

If you're going to recommend a for loop, then I suggest you put the conditions in the for loop as well, instead of using Linq first, then looping through the array.
4

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.