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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With