Check if list contains any of another list

前端 未结 3 2210

I have a list of parameters like this:

public class parameter
{
    public string name {get; set;}
    public string paramtype {get; set;}
    public string          


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 09:48

    You could use a nested Any() for this check which is available on any Enumerable:

    bool hasMatch = myStrings.Any(x => parameters.Any(y => y.source == x));
    

    Faster performing on larger collections would be to project parameters to source and then use Intersect which internally uses a HashSet so instead of O(n^2) for the first approach (the equivalent of two nested loops) you can do the check in O(n) :

    bool hasMatch = parameters.Select(x => x.source)
                              .Intersect(myStrings)
                              .Any(); 
    

    Also as a side comment you should capitalize your class names and property names to conform with the C# style guidelines.

提交回复
热议问题