Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# lambda get distinct list of value conditionally

Tags:

c#

lambda

linq

I have a list of users as given below:

List<User> users = new List<User>();

users.Add(new User(){ UserId = "11", City = "London" });
users.Add(new User(){ UserId = "12", City = "London" });
users.Add(new User(){ UserId = "12", City = "London" });
users.Add(new User(){ UserId = "11", City = "Newyork" });
users.Add(new User(){ UserId = "14", City = "Virginia" });

Here, I want to get distinct UserIDs those have different City by C# lambda expression

So, in above case I should get a List<string> which will only contains UserId = 11 item because UserId is same but city is different for both the item.

Could you please let me know how would I do this by C# lambda code.

Thanks in advance.

like image 870
nunu Avatar asked Mar 17 '26 01:03

nunu


2 Answers

Something like:

var result = users.GroupBy(u => u.UserId)
                  .Where(g => g.Select(u => u.City).Distinct().Count() > 1)
                  .Select(g => g.Key)
                  .ToList();

should do it.

It takes the {UserId,City} pairs and converts into groups of those pairs indexed by UserId; and then looks for cases where there is more than one city in the group. Finally taking the key from the groups for the result.

like image 173
Richard Avatar answered Mar 18 '26 13:03

Richard


from u in users group u.City by u.UserId into grp //group on the id
where grp.Distinct().Count() > 1 // we only want those with more than one distinct city
select grp.Key //we want the key
like image 26
Jon Hanna Avatar answered Mar 18 '26 15:03

Jon Hanna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!