我有一个班级
class Test
{
public string FirstProp { get; set; }
public string SecondProp { get; set; }
public string ThirdProp { get; set; }
}
和对象列表
var list = new List<Test>
{
new Test { FirstProp = "xxx", SecondProp = "x2", ThirdProp = "x3" },
new Test { FirstProp = "xxx", SecondProp = "x21", ThirdProp = "x31" },
new Test { FirstProp = "yyy", SecondProp = "y2", ThirdProp = "y3" },
new Test { FirstProp = "yyy", SecondProp = "y21", ThirdProp = "y31" },
new Test { FirstProp = "xxx", SecondProp = "x22", ThirdProp = "x32" },
};
我需要选择第一个FirstProp记录:
FirstProp = "xxx", SecondProp = "x2", ThirdProp = "x3"
FirstProp = "yyy", SecondProp = "y2", ThirdProp = "y3"
如何使用linq
以最佳方式执行此操作?
答案 0 :(得分:7)
您可以在属性FirstProp
上使用GroupBy
,然后获取First
:
list.GroupBy(x => x.FirstProp).Select(g => g.First())
答案 1 :(得分:3)
list.GroupBy (l => l.FirstProp).Select (l => l.First ())
会在这里工作,但你需要确定你需要从每个小组中选择哪个项目(首先并不总是一个不错的选择)
答案 2 :(得分:0)
您需要使用Distinct
属性
var result = list.DistinctBy(t => t.FirstProp);