LINQ: Distinct values

前端 未结 7 1149
一生所求
一生所求 2020-11-22 16:29

I have the following item set from an XML:

id           category

5            1
5            3
5            4
5            3
5            3
<
7条回答
  •  遇见更好的自我
    2020-11-22 17:00

    I'm a bit late to the answer, but you may want to do this if you want the whole element, not only the values you want to group by:

    var query = doc.Elements("whatever")
                   .GroupBy(element => new {
                                 id = (int) element.Attribute("id"),
                                 category = (int) element.Attribute("cat") })
                   .Select(e => e.First());
    

    This will give you the first whole element matching your group by selection, much like Jon Skeets second example using DistinctBy, but without implementing IEqualityComparer comparer. DistinctBy will most likely be faster, but the solution above will involve less code if performance is not an issue.

提交回复
热议问题