Getting index of duplicate items in a list in c#

后端 未结 4 1399
星月不相逢
星月不相逢 2021-01-18 21:10

I am looking for a way to get the index of all elements in a list from a keyword search within the list. So for example my list has:

Hello World
Programming          


        
4条回答
  •  清歌不尽
    2021-01-18 21:53

    Since you know you're looking for ALL occurrences and therefore you must traverse the entire list anyway, you'll gain a lot of readability over using IndexOf by simply examining each element yourself:

    var i=0;
    foreach(var value in searchInList)
    {
       if(value == "Hello World")
          foundHelloWorld.Add(i); //foundHelloWorld must be an IList
    
       i++;
    }
    

    You can also use an overload of the Linq Select method that incorporate's the element's index in the source collection; this should be highly readable (and thus maintainable) to Linq-experienced programmers:

    foundHelloWorld = searchInList
                         .Select((v,i)=>new {Index = i, Value = v})
                         .Where(x=>x.Value == "Hello World")
                         .Select(x=>x.Index)
                         .ToList();
    

    The above code takes the list and transforms the string into a simple anonymous type incorporating each item's place in the original list. Then, it filters down to only matching elements, and then it projects out the Index (which didn't change through the filtering) into a new List object. However, all this transformation will make this solution perform slower, because this statement will traverse the entire list multiple times.

提交回复
热议问题