user1526912
user1526912

Reputation: 17280

How to find the difference between 2 IEnumerable objects

I have 2 list of guids as:

IEnumerable<dynamic> userids = null;
IEnumerable<dynamic> lsCheckedUsers = null;

The userids and lsCheckedUsers list are populated from a SQL database using dapper.

I now wish to find all userids that are not in lsCheckedUsers.

I have tried the following

var userdifference = userids.Where(i => !lsCheckedUsers.Contains(lsCheckedUsers));
var userdifference = userids.Except(lsCheckedUsers);

None of the above actual returns the difference between the 2.

How do I get the difference of guids that do not exist in both.

I am certain that lsCheckedUsers has Guids that are in userids

Upvotes: 8

Views: 8521

Answers (4)

paparazzo
paparazzo

Reputation: 45096

Enumerable has an Except method

Enumerable.Except Method (IEnumerable, IEnumerable)

And use String or GUID.
It will compare values for equals.

HashSet ExceptWith would probably have better performance.
But cannot use HashSet if you need to allow duplicates.

HashSet.ExceptWith Method

Upvotes: 1

Ian Gardner
Ian Gardner

Reputation: 374

This is correct:

var userdifference = userids.Except(lsCheckedUsers);

It will work if both of your IEnumerable<dynamic> actually contain Guids. Print out or inspect the items in each to make sure they are Guids.

You should really be using IEnumerable<Guid> and cast the incoming items to Guids if this is what you are expecting. It will hopefully prevent errors like the one you are potentially seeing.

Upvotes: 14

itsme86
itsme86

Reputation: 19526

You have:

var userdifference = userids.Where(i => !lsCheckedUsers.Contains(lsCheckedUsers));

But I think you mean:

var userdifference = userids.Where(i => !lsCheckedUsers.Contains(i));

Update:

To everyone marking down these answers because of "reference" comparisons, consider that Guid is a value type so its equality is evaluated differently. Try this simple test to convince yourself:

var guid = Guid.NewGuid();
var guids = new[] { new Guid(guid.ToString()) };

Console.WriteLine(guids.Contains(guid));

You'll see that the result is True.

Upvotes: 1

Mathieu Guindon
Mathieu Guindon

Reputation: 71217

Something along those lines..

var difference = list1.Where (e => !list2.Any(a => a == e))

Upvotes: 2

Related Questions