Search code examples
c#listlinq

Searching a list that contains a certain int from another list


I find myself in a need to create a new list that has certain properties on a given list.

For example, I have this list:

List<string> aStringList = new List<string>() {
                                                "meat1", "meat2",
                                                "tomato3", "tomatoes4",
                                                "brocolli5", "brocoli6"
                                               };

Then with a given parameter of

List<int> aIntList = new List<int>() { 1, 2, 6 };

I need to generate a new list that contains only meat1, meat2, brocoli6.

I know that I can use this:

 var matchingvalues = aStringList.Where(s => s.Contains(aIntList [0].ToString())
                                          || s.Contains(aIntList [1].ToString())
                                          || s.Contains(aIntList [2].ToString())
                                        );

But it’s ugly and it’s not dynamic.

How else can I improve this?


Solution

  • It's not fully clear what aIntList contains. If it contains indexes then the answer by @dmitry-bychenko is good. But if the second list contains part of content then you could use this approach:

    List<string> aStringList = new List<string>() {
        "meat1", "meat2",
        "tomato3", "tomatoes4",
        "brocolli5", "brocoli6"
    };
    
    List<int> aIntList = new List<int>() { 1, 6, 2 };
    
    var matchingvalues = aStringList.Where(s => aIntList.Any(a=>s.Contains(a.ToString())));
    

    It allows you to avoid explicit iteration in the Where condition.

    Another way is to use Join, but it requires parsing the string first. It could look like this:

    var matchingvalues2 = aStringList.Join(
        aIntList,
        s => int.Parse(Regex.Match(s, @"\d+$", RegexOptions.RightToLeft).Value),
        i => i,
        (s, i) => s
    );