与 LINQ 的类属性不同 [英] Distinct by property of class with LINQ

查看:20
本文介绍了与 LINQ 的类属性不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个收藏:

List<Car> cars = new List<Car>();

汽车由其属性CarCode唯一标识.

Cars are uniquely identified by their property CarCode.

我收藏了三辆汽车,其中两辆具有相同的 CarCode.

I have three cars in the collection, and two with identical CarCodes.

如何使用 LINQ 将此集合转换为具有唯一 CarCode 的汽车?

How can I use LINQ to convert this collection to Cars with unique CarCodes?

推荐答案

可以使用分组,从每个组中得到第一辆车:

You can use grouping, and get the first car from each group:

List<Car> distinct =
  cars
  .GroupBy(car => car.CarCode)
  .Select(g => g.First())
  .ToList();

这篇关于与 LINQ 的类属性不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆