Linq to get distinct property
This question already has an answer here:
Rewrite your GetHashCode()
function:
public int GetHashCode(MY_DATA_TABLE obj)
{
return obj.CODE.GetHashCode();
}
Rule is, that both Equals and GetHashCode()
should check the same properties, and you checking just Code in Equals()
and whiole object in GetHashCode()
另一种选择是如果Version
不重要,则在每个组中进行一个组并取其中的第一个值。
var mapCodes = (from mtc in GetAllData()
group mtc by mtc.Code into grp
select grp.First()).ToList();
You can use MoreLinq's DistinctBy
var mapCodes = (from mtc in GetAllData()
select mtc).DistinctBy(x=>x.Code).ToList();
Or just:
var mapCodes = GetAllData().DistinctBy(x=>x.Code).ToList();
Or you can correct the GetHashCode method as mentioned in the comments
链接地址: http://www.djcxy.com/p/51294.html上一篇: 来自列表的C#不同列表
下一篇: Linq获得独特的财产