C#的lambda得到的值不同的条件清单 [英] C# lambda get distinct list of value conditionally
问题描述
我有一个用户列表,如下所示:
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" });
在这里,我想获得的不同的用户ID那些有不同的城市按 C#lambda表达式
因此,在上述情况下,我应该得到一个列表<串>
这将只包含用户ID = 11项,因为用户ID是相同的,但城市是两个项目不同。
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.
能否请你让我知道如何会我用C#的lambda代码做到这一点。
Could you please let me know how would I do this by C# lambda code.
在此先感谢。
推荐答案
是这样的:
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.
这需要在{用户ID,市}对,并将其转换成用户ID收录那些对群体;然后查找那里是该组中的一个以上的城市的情况。最后取得从基为结果的关键。
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.
这篇关于C#的lambda得到的值不同的条件清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!