How to use Linq to check if a list of strings contains any string in a list

后端 未结 5 1557
别跟我提以往
别跟我提以往 2021-02-05 07:12

I\'m constructing a linq query that will check is a string in the DB contains any of the strings in a list of strings.

Something like.

query = query.Whe         


        
5条回答
  •  余生分开走
    2021-02-05 07:37

    EDIT: This answer assumed that tags was a collection of strings...

    It sounds like you might want:

    var list = new List { ... };
    var query = query.Where(x => x.tags.Any(tag => list.Contains(tag));
    

    Or:

    var list = new List { ... };
    var query = query.Where(x => x.tags.Intersect(list).Any());
    

    (If this is using LINQ to SQL or EF, you may find one works but the other doesn't. In just LINQ to Objects, both should work.)

    To get the count, you'd need something like:

    var result = query.Select(x => new { x, count = x.tags.Count(tag => list.Contains(tag)) })
                      .Where(pair => pair.count != 0);
    

    Then each element of result is a pair of x (the item) and count (the number of matching tags).

提交回复
热议问题