简体   繁体   中英

How do I check if one list contains 2 elements of another list with more elements?

I am working on a application in C# and I am stuck at something.

I have 2 list with strings. List1 has 4 elements and List2 has 6 elements. Now I need check if 2 elements from List1 exists in List2, no matter the order.

I have been stuck with this and I don't know how to code it. Does someone have any suggestions?

List<string> List1 = new List<string>();
    List1.Add("blue");
    List1.Add("red");
    List1.Add("orange");
    List1.Add("aqua");

List<string> List2 = new List<string>();
    List1.Add("orange");
    List1.Add("aqua");
    List1.Add("blue");
    List1.Add("red");
    List1.Add("purple");
    List1.Add("pink");

if () //List2 contains 2 elements of list1 no matter the order

You can use Intersect Method. Try like:

 if (list1.Intersect(list2).Count()>=2)
if(List2.Intersect(List1).Count == 2){}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM