C# lambda get distinct list of value conditionally

2020-06-27 03:43发布

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.

标签: c# linq lambda
3条回答
Fickle 薄情
2楼-- · 2020-06-27 04:23
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楼-- · 2020-06-27 04:45

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.

查看更多
看我几分像从前
4楼-- · 2020-06-27 04:46
var list = users.GroupBy(Obj=>new {Obj.UserID,Obj.City}).Distinct();
查看更多
登录 后发表回答