Search code examples
c#listlambdageneric-listgeneric-lambda

Find item index with lambda or linkq in c#


Hi i can't speak english well forgive me if ill confuse you.

in c# i have 3 String List.

list_one: list of file address.

list_two: list of MD5 that makes with list_one.

list_three: list of MD5 that makes with list_two but in this list i collect duplicate item from list_two

Question :

How can i get each item in list_three and search that in list_two then return that index.

but i dont like to use for or foreach because that will slow my application.

how can do that with linq or lambda or any fastest way.

my lists Image


Solution

  • No 1 foeach isn't slower. But to answer what you want is simple one liner like this.

    using System.Linq;  
    
    List<string> list = new List<string>{"a","b","c","d"};
    List<string> list2 = new List<string>{"a","c"};  
    
    var result = list.Select((a, b) => new {Value = a, Index = b})
                  .Where(x => list2.Any(d => d == x.Value))
                  .Select(c => c.Index).ToArray();
    

    now result contains all the match indexes.Fiddle