使用linq检查列表中的所有项目是否都出现在另一个列表中 [英] checking if all the items in list occur in another list using linq

查看:111
本文介绍了使用linq检查列表中的所有项目是否都出现在另一个列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到问题。



例如:

pre> 列表1:10,15,20
列表2:10,13,14,15,20,30,45,54,67,87

如果<$ c $中的所有项目都应该得到 TRUE c> list 1 发生在列表2 中。所以上面的例子应该返回 TRUE



像你可以看到我不能使用 sequenceEquals



任何想法?



编辑:



list2实际上不是一个列表,它是sql中的一个列,thas具有以下值:
< id> 673< / id>< id> 698& /id><id>735</id>&>1118</id>&>1120</id><id>25353</id>/code>.



在linq我做了以下查询感谢Jon Skeets帮助:

  var query = from e in db 
其中e.taxonomy_parent_id == 722
select e.taxonomy_item_id;

查询为 IQueryable

  var query2 = from e in db 
where query.Contains(e.taxonomy_item_id)
其中! lsTaxIDstring.Except(e.taxonomy_ids.Replace(< id>,)
.Replace(< / id>,)
.Split(',')。 ToList())
.Any()
select e.taxonomy_item_id;

但现在我得到错误本地序列不能在LINQ中使用

解决方案

如何执行查询运算符

  if(!list1.Except(list2).Any())

这是关于我能想到的最简单的方法。您可以显式创建集等等:

  HashSet< int> set2 = new HashSet< int>(list2); 
if(!list1.Any(x => set2.Contains(x)))

但我期望几乎是的实现 c>

$


I am stuck with a problem here. I am trying to compare items in a list to another list with much more items using linq.

For example:

list 1: 10,15,20
list 2: 10,13,14,15,20,30,45,54,67,87

I should get TRUE if all the items in list 1 occur in list 2. So the example above should return TRUE

Like you can see I can't use sequenceEquals

Any ideas?

EDIT:

list2 is actually not a list it is a column in sql thas has following values: <id>673</id><id>698</id><id>735</id><id>1118</id><id>1120</id><id>25353</id>.

in linq I did the following queries thanks to Jon Skeets help:

var query = from e in db
            where e.taxonomy_parent_id == 722
            select e.taxonomy_item_id;

query is IQueryable of longs at this moment

var query2 = from e in db
             where query.Contains(e.taxonomy_item_id)
             where !lsTaxIDstring.Except(e.taxonomy_ids.Replace("<id>", "")
                                                       .Replace("</id>", "")
                                                       .Split(',').ToList())
                                 .Any()
             select e.taxonomy_item_id;

But now I am getting the error Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator.

解决方案

How about:

if (!list1.Except(list2).Any())

That's about the simplest approach I can think of. You could explicitly create sets etc if you want:

HashSet<int> set2 = new HashSet<int>(list2);
if (!list1.Any(x => set2.Contains(x)))

but I'd expect that to pretty much be the implementation of Except anyway.

这篇关于使用linq检查列表中的所有项目是否都出现在另一个列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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