C# lambda get distinct list of value conditionally

2020-06-27 03:41发布

问题:

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.

回答1:

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.



回答2:

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


回答3:

var list = users.GroupBy(Obj=>new {Obj.UserID,Obj.City}).Distinct();


标签: c# linq lambda