Linq to get distinct property

This question already has an answer here:

  • LINQ's Distinct() on a particular property 17 answers

  • 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获得独特的财产