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

查看:47
本文介绍了与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将此集合转换为具有唯一CarCodes的Cars?

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天全站免登陆