Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if listA contains any elements not in listB

Tags:

c#

linq

I have two lists:

List<int> listA     
List<int> listB

How to check using LINQ if in the listA exists an element wchich deosn't exists in the listB ? I can use the foreach loop but I'm wondering if I can do this using LINQ

like image 466
Tony Avatar asked Mar 01 '12 21:03

Tony


People also ask

How do you check if an element is not in a list?

In & Not in operators “in” operator − This operator is used to check whether an element is present in the passed list or not. Returns true if the element is present in the list otherwise returns false.

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 variable is not in a list Python?

a_list = [1, 2, 3, 4, 5] # Checks if the variable "a_list" is a list if type(a_list) == list: print("Variable is a list.") else: print("Variable is not a list.") This results in: "Variable is a list."


3 Answers

listA.Except(listB) will give you all of the items in listA that are not in listB

like image 119
cadrell0 Avatar answered Oct 16 '22 13:10

cadrell0


if (listA.Except(listB).Any())
like image 33
SLaks Avatar answered Oct 16 '22 14:10

SLaks


listA.Any(_ => listB.Contains(_))

:)

like image 17
the_joric Avatar answered Oct 16 '22 13:10

the_joric