Check if list contains any of another list

前端 未结 3 2209

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:30

    If both the list are too big and when we use lamda expression then it will take a long time to fetch . Better to use linq in this case to fetch parameters list:

    var items = (from x in parameters
                    join y in myStrings on x.Source equals y
                    select x)
                .ToList();
    
    0 讨论(0)
  • 2020-12-02 09:47

    Here is a sample to find if there are match elements in another list

    List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 };
    List<int> nums2 = new List<int> { 1, 3, 6, 9, 12};
    
    if (nums1.Any(x => nums2.Any(y => y == x)))
    {
        Console.WriteLine("There are equal elements");
    }
    else
    {
        Console.WriteLine("No Match Found!");
    }
    
    0 讨论(0)
  • 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<T> 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.

    0 讨论(0)
提交回复
热议问题