C# Check if a List is a part of another List [duplicate]

邮差的信 提交于 2020-01-01 11:45:00

问题


I have two lists as follows

 var query1 = from enrollments in db.Enrollments
             where enrollments.studentID == studentID && enrollments.result >= 50 && enrollments.enrolled == false
             select enrollments.subjectID;
 var query2 = from prerequisites in db.Prerequisites
              where prerequisites.subjectID == subjectID
              select prerequisites.prerequisiteID;

Now I want to make sure that all the numbers in query2 exist in query1. In other words, I want to ensure that query2 is a part of query1

Any ideas?

P.S

-You can be sure that subjectID and prerequisiteID are the same thing

-I can convert query1 and query2 to lists like that query.ToList()


回答1:


bool results =  query2.All(i=>query1.Contains(i));

related questions below :

Determine if a sequence contains all elements of another sequence using Linq

Check whether an array is a subset of another




回答2:


You can simply check to see that the set difference between query2 and query1 is the empty set:

var isSubset = !query2.Except(query1).Any();

See the LINQ methods Enumerable.Except and Enumerable.Any.




回答3:


Have you looked at using Intersect (http://msdn.microsoft.com/en-us/library/bb460136.aspx) Given two IEnumerables it will return a list of any values that exist in both.

var presentInBoth = query1.Intersect(query2)

You may well need to call .ToList() query1 and query2 to make them IEnumerable



来源:https://stackoverflow.com/questions/16789336/c-sharp-check-if-a-list-is-a-part-of-another-list

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