user677607
user677607

Reputation:

How do I use Linq to find the elements of a list that are not present in another list?

I have 2 List of String variables:

List<string> stringList1
List<string> stringList2 

where stringList2 is a subset of stringList1

now I want all the elements on stringList1 that aren't in stringList2

How do I achieve this using Linq?

Upvotes: 4

Views: 2122

Answers (2)

Ry-
Ry-

Reputation: 224952

Use this LINQ expression:

from string x in stringList1 where !stringList2.Contains(x) select x;

I'm sure there's a built in method, but that's the LINQ. (I don't have VC# with me right now...)

Upvotes: 2

Anthony Pegram
Anthony Pegram

Reputation: 126884

You want to use the Except extension method on IEnumerable<T>

var results = stringList1.Except(stringList2);

Upvotes: 14

Related Questions