checking if all the items in list occur in another list using linq

我们两清 提交于 2019-12-13 13:24:45

问题


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.


回答1:


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.




回答2:


This should be what you want:

!list1.Except(list2).Any() 



回答3:


var result = list1.All(i => list2.Any(i2 => i2 == i));


来源:https://stackoverflow.com/questions/8486707/checking-if-all-the-items-in-list-occur-in-another-list-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!