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

前端 未结 9 465
爱一瞬间的悲伤
爱一瞬间的悲伤 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:24

    something like this:

    List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
    List<string> test2 = new List<string> { "joe@bob.com", "test@sam.com" };
    
    var res = test2.Where(f => test1.Count(z => f.Contains(z)) == 0)
    

    Live example: here

    0 讨论(0)
  • 2020-12-01 00:24
    List<string> l = new List<string> { "@bob.com", "@tom.com" };
    List<string> l2 = new List<string> { "joe@bob.com", "test@bob.com" };
    List<string> myboblist= (l2.Where (i=>i.Contains("bob")).ToList<string>());
    foreach (var bob in myboblist)
        Console.WriteLine(bob.ToString());
    
    0 讨论(0)
  • 2020-12-01 00:27
    var output = emails.Where(e => domains.All(d => !e.EndsWith(d)));
    

    Or if you prefer:

    var output = emails.Where(e => !domains.Any(d => e.EndsWith(d)));
    
    0 讨论(0)
  • 2020-12-01 00:29
    var test2NotInTest1 = test2.Where(t2 => test1.Count(t1 => t2.Contains(t1))==0);
    

    Faster version as per Tim's suggestion:

    var test2NotInTest1 = test2.Where(t2 => !test1.Any(t1 => t2.Contains(t1)));
    
    0 讨论(0)
  • 2020-12-01 00:36

    I think this would be easiest one:

    test1.ForEach(str => test2.RemoveAll(x=>x.Contains(str)));
    
    0 讨论(0)
  • 2020-12-01 00:42

    No need to use Linq like this here, because there already exists an extension method to do this for you.

    Enumerable.Except<TSource>

    http://msdn.microsoft.com/en-us/library/bb336390.aspx

    You just need to create your own comparer to compare as needed.

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