Search code examples
c#linqc#-4.0lambdalinq-to-entities

Get List of Item that contains of another list


Please consider this string list:

Afghanistan, Albania, Algeria, El Salvador,
Equatorial, Guinea, Eritrea, Estonia
Ethiopia, Panama, Papua, Paraguay
Peru, Togo, Trinidad & Tobago, Tunisia, Turkey

and I have another list:

tan, ia, Tu

I want all countries that contains tan or ia or Tu. How I can do this without foreach loop?

thanks


Solution

  • Try something like that;

    var listA = new List<string> {"Afghanistan", "England"};
    var listB = new List<string> {"afg"};
    listA = listA.Where(x => listB.Any(k => x.IndexOf(k, StringComparison.OrdinalIgnoreCase) > -1)).ToList();
    

    Also, I have ignored the case sensitive. If you want to perform case sensitive use x.IndexOf(k, StringComparison.Ordinal) instead of x.IndexOf(k, StringComparison.OrdinalIgnoreCase).