Pat
Pat

Reputation: 727

List Index Search

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;

Upvotes: 1

Views: 634

Answers (2)

O. R. Mapper
O. R. Mapper

Reputation: 20780

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.

Upvotes: 1

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48600

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

Upvotes: 4

Related Questions