且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用linq检查列表中的所有项目是否都出现在另一个列表中

更新时间:2023-11-26 08:35:40

如何执行查询运算符

  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.