如何使用Linq检查字符串列表中是否包含列表中的任何字符串 [英] How to use Linq to check if a list of strings contains any string in a list

查看:168
本文介绍了如何使用Linq检查字符串列表中是否包含列表中的任何字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构造一个linq查询,该查询将检查DB中的字符串是否包含字符串列表中的任何字符串.

类似.

  query = query.Where(x => x.tags.contains(-我的字符串列表中的任何项目-)); 

我还想知道列表中有多少个项目匹配.

任何帮助将不胜感激.

更新:我应该提到标签是一个字符串而不是列表.在查询实际运行之前,我还要添加一些与标记无关的位置.这是针对实体框架运行的.

解决方案

此答案假定 tags 是字符串的集合...

听起来您可能想要:

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

或者:

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

(如果这是使用LINQ to SQL或EF,您可能会发现其中一个可行,而另一个却不可行.仅在LINQ to Objects中,两个都应该可行.)

要获得计数,您需要类似:

  var结果= query.Select(x =>新{x,count = x.tags.Count(tag => list.Contains(tag))}).where(pair => pair.count!= 0); 

然后,结果 result 的每个元素都是一对 x (该项)和 count (匹配标签的数量).

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.Where(x => x.tags
                   .Contains(--any of the items in my list of strings--));

I'd also like to know how many of the items in the list were matched.

Any help would be appreciated.

Update: I should have mentioned that tags is a string not a list. And I am adding on a couple more wheres that are not related to tags before the query actually runs. This is running against entity framework.

解决方案

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

It sounds like you might want:

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

Or:

var list = new List<string> { ... };
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).

这篇关于如何使用Linq检查字符串列表中是否包含列表中的任何字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆