In C#, how can I filter a list using a StartsWith() condition of another list?

35,577

Solution 1

var resultList = fullNameList.Where(r => searchList.Any(f=>r.StartsWith(f)));

Solution 2

The following LINQ query seems literate-programming-like to me and pretty straightforward to read & maintain later,:

var searchList = new List<string> { "Joe", "Bob" };

var fullNameList = new List<string>
    {
        "Joe Thompson",
        "Bob Jones",
        "Bob Smith",
        "Billy Smith",
        "Joe Williams"
    };

var joesAndBobs = from name in fullNameList
                  from firstName in searchList
                  where name.StartsWith(firstName)
                  select name;

foreach (string str in joesAndBobs)
    Console.WriteLine(str);

However, it may perform worse than solutions previously posted. They use .Any() method of IEnumerable<T>, it stops after finding the first matching first name for any dude, while mine continues through all the Joes, Bobs and Mikes anyway.

Solution 3

Something like:

fullNameList.Where(c=>searchList.Any(f=>c.StartsWith(f))) 
Share:
35,577

Related videos on Youtube

leora
Author by

leora

Updated on July 22, 2022

Comments

  • leora
    leora almost 2 years

    Lets say I have a list of strings:

    var searchList = new List<string>();
    searchList.Add("Joe"):
    searchList.Add("Bob");
    

    and I have another list

    var fullNameList = new List<string>();
    fullNameList.Add("Joe Thompson"):
    fullNameList.Add("Bob Jones");
    fullNameList.Add("Bob Smith");
    fullNameList.Add("Billy Smith");
    fullNameList.Add("Joe Williams");
    

    I now want to filter the fullNameList based on if it exists in the search list but I am not doing a direct match but rather a "starts with" match. So in my example, after filtering I would want this to be the results

    "Joe Thompson"
    "Bob Jones"
    "Bob Smith"
    "Joe Williams"
    

    (as you can see the record starting with Billy was not included as it didn't start with any items in the search list)

    I could do this "manually" like this:

     var resultList = fullNameList.Where(r=> r.StartsWith("Joe") || r.StartsWith("Bob"));
    

    but I want it to be dynamic (as there might be more items in the search list added in the future).

    I could do this in a loop like this:

     var resultsList = new List<string>();
    
     foreach (var item in searchList)
     { 
          resultsList.AddRange(fullNameList.Where(r=>r.StartsWith(item));
     } 
    

    but wanted to see if there anyway to do a Startswith on a list as opposed to a single string in a single line of linq code?