LINQ查询来获取列表中的不同值 [英] Linq query to get the distinct values in a list
本文介绍了LINQ查询来获取列表中的不同值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想这是我的成员类
类会员
{
公共字符串categoryId {搞定;组; }
公共字符串MemberName {搞定;组; }
公众诠释距离{搞定;组; }
}
和,这是清单。
VAR名单=新名单,LT;会员>();
list.Add(新{=类别ID01,MemberName =安迪距离= 3});
list.Add(新{=类别ID02,MemberName =约翰距离= 5});
list.Add(新{=类别ID01,MemberName =马修距离= 7});
list.Add(新{=类别ID03,MemberName =巴卡拉距离= 2});
任何人都可以请建议逻辑/ LINQ查询来获取具有最短距离不同/独特的categoryID名单
的
输出
应该是:
list.Add(新{=类别ID01,MemberName =安迪距离= 3});
list.Add(新{=类别ID02,MemberName =约翰距离= 5});
list.Add(新{=类别ID03,MemberName =巴卡拉距离= 2});
解决方案
这应该给你你需要什么:
VAR分组= list.GroupBy(项目=> item.CategoryId);
VAR最短= grouped.Select(GRP => grp.OrderBy(项目=> item.Distance)。首先());
据第一组与同一的CategoryId
,然后选择从每个组(由距离
排序)第一。
Suppose this is my member class
class Member
{
public string CategoryId { get; set; }
public string MemberName { get; set; }
public int Distance { get; set; }
}
And, this is list.
var list = new List<Member>();
list.Add(new { CategoryId = "01", MemberName="andy" Distance=3});
list.Add(new { CategoryId = "02", MemberName="john" Distance=5});
list.Add(new { CategoryId = "01", MemberName="mathew" Distance=7});
list.Add(new { CategoryId = "03", MemberName="bakara" Distance=2});
Can anyone please suggest the logic/ linq query to get the List having distinct/unique categoryID with Shortest distance.
The output
should be :
list.Add(new { CategoryId = "01", MemberName="andy" Distance=3});
list.Add(new { CategoryId = "02", MemberName="john" Distance=5});
list.Add(new { CategoryId = "03", MemberName="bakara" Distance=2});
解决方案
This should give you what you need:
var grouped = list.GroupBy(item => item.CategoryId);
var shortest = grouped.Select(grp => grp.OrderBy(item => item.Distance).First());
It first groups the items with the same CategoryId
, then selects the first from each group (ordered by Distance
).
这篇关于LINQ查询来获取列表中的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文