LINQ query to find if items in a list are contained in another list

前端 未结 9 466
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-01 00:14

I have the following code:

List test1 = new List { \"@bob.com\", \"@tom.com\" };
List test2 = new List

        
相关标签:
9条回答
  • 2020-12-01 00:42
    List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
    List<string> test2 = new List<string> { "joe@bob.com", "test@sam.com", "bets@tom.com" };
    
    var result = (from t2 in test2
                  where test1.Any(t => t2.Contains(t)) == false
                  select t2);
    

    If query form is what you want to use, this is legible and more or less as "performant" as this could be.

    What i mean is that what you are trying to do is an O(N*M) algorithm, that is, you have to traverse N items and compare them against M values. What you want is to traverse the first list only once, and compare against the other list just as many times as needed (worst case is when the email is valid since it has to compare against every black listed domain).

    from t2 in test we loop the email list once.

    test1.Any(t => t2.Contains(t)) == false we compare with the blacklist and when we found one match return (hence not comparing against the whole list if is not needed)

    select t2 keep the ones that are clean.

    So this is what I would use.

    0 讨论(0)
  • 2020-12-01 00:44
    bool doesL1ContainsL2 = l1.Intersect(l2).Count() == l2.Count;
    

    L1 and L2 are both List<T>

    0 讨论(0)
  • 2020-12-01 00:45

    Try the following:

    List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
    List<string> test2 = new List<string> { "joe@bob.com", "test@sam.com" };
    var output = from goodEmails in test2
                where !(from email in test2
                    from domain in test1
                    where email.EndsWith(domain)
                    select email).Contains(goodEmails)
                select goodEmails;
    

    This works with the test set provided (and looks correct).

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