C# lambda 有条件地获取不同的值列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12176389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:21:24  来源:igfitidea点击:

C# lambda get distinct list of value conditionally

c#linqlambda

提问by nunu

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 Cityby C# lambda expression

在这里,我想通过以下方式获得具有不同城市不同用户 IDC# 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.

所以,在上面的例子中,我应该得到一个List<string>只包含 UserId = 11 的项目,因为 UserId 是相同的,但两个项目的城市不同。

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

你能否让我知道我将如何通过 C# lambda 代码做到这一点。

Thanks in advance.

提前致谢。

采纳答案by Richard

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.

它采用 {UserId,City} 对并转换为由 UserId 索引的那些对的组;然后查找组中存在多个城市的情况。最后从组中取出密钥以获得结果。

回答by Jon Hanna

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

回答by Sanjay Gupta

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