1

I have a List item

List<string> xmlValue = new List<string>();

In this I have Item {"English","Spanish","French","Hindi","English","English"} I need to search all English item along with its Index(item index). I wrote the below code it returns index only for 1 item .How can get the index for the next item also.

    string search = "English";
    int index = xmlValue.Select((item, i) => new { Item = item, Index = i })
    .First(x => x.Item == search).Index;
Habib
  • 219,104
  • 29
  • 407
  • 436
Pat
  • 727
  • 1
  • 10
  • 22
  • Where do you want the indices to be stored? In your `int` variable `index`, you can only store one index at a time. – O. R. Mapper Jul 02 '12 at 10:58

2 Answers2

4
List<string> xmlValue = new List<string>() 
                 {"English", "Spanish", "French", "Hindi", "English", "English"};

string search = "English";

int[] result = xmlValue.Select((b, i) => b.Equals(search) ? i : -1)
                       .Where(i => i != -1).ToArray();
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • Thanks Nikhil it was a quick reply. – Pat Jul 02 '12 at 11:02
  • @MahmoudGamal: I'm not sure about him wanting only the first *two* indices. Note how he doesn't use a single plural form in his whole question, even where one would be required. Therefore, I'd surmise that he's looking for the indices of all following items, not just the one next item. – O. R. Mapper Jul 02 '12 at 11:20
1

I'd opt against using the LINQ extension methods in this case and use an "old-fashioned" loop:

string search = "English";

var foundIndices = new List<int>(xmlValue.Count);
for (int i = 0; i < xmlValue.Count; i++) {
    if (xmlValue[i] == search) {
        foundIndices.Add(i);
    }
}

It's simply more readable like this in my opinion; also, the foundIndices list never holds any unwanted values.

O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114
  • @Reniuz: Matter of taste then. This loop IMO clearly shows what's being looked for and what's added, while with labmda expressions, some tricks with invalid indices that later get filtered out have to be performed. Shorter is not always better :-) – O. R. Mapper Jul 02 '12 at 11:10
  • @christopherPeter: Create a list with a large amount of items and run the two solutions on it while measuring time. [This](http://www.alexyork.net/blog/2008/09/14/performance-of-foreach-loops-vs-linq/), [this](http://stackoverflow.com/questions/1044236/nested-foreach-vs-lambda-linq-query-performancelinq-to-objects) and [this](http://www.schnieds.com/2009/03/linq-vs-foreach-vs-for-loop-performance.html) may provide starting points. – O. R. Mapper Jul 02 '12 at 11:24