简体   繁体   中英

how to compare two lists using C#?

I have two lists how can I check if list1 has some items that are from list2

for ie i have:

list1 = ["car","424", "fwe"]
list2 = ["car", "cat"]

maybe something like this:

if list1 has elements from  list2

then return true

您可以使用LINQ IntersectExcept功能Except

您可以使用与任何相交:

list1.Intersect(list2).Any()

The best solution really depends on the specifics of your situation.

For instance, you could compare each pair of elements, which would be a very straightforward implementation. However, this isn't particularly efficient if the lists are long.

A second option would be to add all the elements of one list to a HashSet, and then try to add all the elements of the second list. If there is an element in common, the HashSet Add() method will return false when you try to add the duplicate. This will be faster for large lists, but requires additional memory, and may produce less readable code.

另一种可能的方案

list1.Any(e => list2.Contains(e));

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