LINQ distinct on class item?

孤街浪徒 提交于 2019-12-13 17:04:04

问题


Note this question is similar this one except I'm not working with linq-to-sql, so the "let" is not usable.

Basically I have a select of the type

... .Select(c => new SampleClass { Id = c.Location.Name, Name = c.Location.Name }).Distinct().ToList()

which used to work when I just had

... .Select(c => c.Location.Name).Distinct().ToList()

How would I make a distinct call on one of the items within the SampleClass?


回答1:


You can group items by the key, and then select what item from the group you want to use as value. I use FirstOrDefault as an example:

... .Select(c => new SampleClass { Id = c.Location.Name, Name = c.Location.Name })
    .GroupBy(c => c.Id)
    .Select(group => group.FirstOrDefault())
    .ToList()



回答2:


Is this what you need: http://sprokhorenko.blogspot.com/2009/11/convenient-distinct.html ?

This is an extension for IEnumerable that allows you to .Distinct() for any field (or even several ones using lambdas), which creates IEqualityComparer for you on the fly.



来源:https://stackoverflow.com/questions/1930654/linq-distinct-on-class-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!