Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 846
Ozkan Avatar asked Dec 13 '22 07:12

Ozkan


1 Answers

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.

like image 119
Jon Skeet Avatar answered Dec 14 '22 22:12

Jon Skeet