Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check list A contains any value from list B?

Tags:

c#

list

linq

List A:

1, 2, 3, 4 

List B:

2, 5 

How to check if list A contains any value from list B?

e.g. something like A.contains(a=>a.id = B.id)?

like image 633
wahaha Avatar asked Sep 11 '12 19:09

wahaha


People also ask

How do you check if a list contains any value from another list?

Using any() along with a generator expression: list1 = ['item1','item2','item3'] list2 = ['item4','item5','item3'] if any(x in list1 for x in list2): print("Duplicates found.") else: print("No duplicates found.")

How do you check if a list contains any value from another list in Java?

ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

How do I see if a list contains a list?

Below programs illustrate the contains() method in List: Program 1: Demonstrate the working of the method contains() in List of integer. Program 2: Demonstrate the working of the method contains() in List of string. Practical Application: In search operations, we can check if a given element exists in a list or not.


1 Answers

If you didn't care about performance, you could try:

a.Any(item => b.Contains(item)) // or, as in the column using a method group a.Any(b.Contains) 

But I would try this first:

a.Intersect(b).Any() 
like image 129
Justin Niessner Avatar answered Sep 20 '22 17:09

Justin Niessner