简体   繁体   中英

Select Distinct rows based a particular column value in list

I have the following list Lsit<Car> lstcarIP it has the following data

ID  | Name | Year
0 - Zen    - 1990
1 - Alto   - 2003
3 - Zen    - 2004
4 - Santro - 2000
5 - Alto   - 2003

Irrespective of the ID and year the output list<Car> lstFinal should have

   ID  | Name | Year
    0 - Zen    - 1990
    1 - Alto   - 2003 
    4 - Santro - 2000

or

 ID  | Name | Year 
    3 - Zen    - 2004
    4 - Santro - 2000
    5 - Alto   - 2003

ie If the Name occurs again then only one entry should be added to the list<Car> lstFinal . I tried using LastorDefault or GroupBy

 lstFinal= lstcarIP.GroupBy(s => s.Name)
                            .Where(g => g.Count() > 1)
                             .SelectMany(g => g)
                             .ToList<Car>();

But couldnt get proper result. Could you correct me and point my mistake. Thanks for the help! :)

You just GroupBy , and then get First

 lstFinal = lstcarIP.GroupBy(s => s.Name)
                    .Select(g => g.First())
                    .ToList<Car>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM