C# 如何从一个属性获取非重复值列表

C# 如何从一个属性获取非重复值列表,c#,linq,C#,Linq,我有一个员工列表,其中包含属性类别ID。我想在列出员工类别中提取这些类别 我尝试了这个方法,但得到了重复的类别: List<int> employeeCategories = employees.Select(x => x.CategoryID).ToList(); List employeeCategories=employees.Select(x=>x.CategoryID.ToList(); 我想要所有这些类别,但不要重复 我一直在尝试这样做: List<int

我有一个
员工列表
,其中包含属性
类别ID
。我想在
列出员工类别
中提取这些类别

我尝试了这个方法,但得到了重复的类别:

List<int> employeeCategories = employees.Select(x => x.CategoryID).ToList();
List employeeCategories=employees.Select(x=>x.CategoryID.ToList();
我想要所有这些类别,但不要重复

我一直在尝试这样做:

List<int> employeeCategories = employees.GroupBy(x => x.CategoryID).Select(x => x.First()).Select(x => x.CategoryID).ToList();
List employeeCategories=employees.GroupBy(x=>x.CategoryID).选择(x=>x.First()).选择(x=>x.CategoryID).ToList();
有没有更简单更干净的方法来实现这一点?我是否正确使用了
GroupBy
方法


提前感谢。

这就是
Distinct()
的用途。它将删除所有重复的条目

List<int> employeeCategories = employees.Select(x => x.CategoryID).Distinct().ToList();
List employeeCategories=employees.Select(x=>x.CategoryID.Distinct().ToList();

老实说,我也是这样做的。使用LINQ扩展Distinct()通常也不会按照我想要的方式工作。您可以将其简化为
GroupBy(x=>x.CategoryID)
GroupBy
的结果是一个
i分组
,其中每个项目都有一个
,这是您分组的唯一值。@juharr有趣。非常感谢。