使用linq选择属性的第一个记录

时间:2013-03-20 10:42:03

标签: c# .net linq select

我有一个班级

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以最佳方式执行此操作?

3 个答案:

答案 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);
相关问题