0

我有一堂课

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

4

3 回答 3

8

您可以GroupBy在属性上使用FirstProp,然后获取First

 list.GroupBy(x => x.FirstProp).Select(g => g.First())
于 2013-03-20T10:44:01.920 回答
3
list.GroupBy (l => l.FirstProp).Select (l => l.First ())

将在这里工作,但您需要确定您需要从每个组中获取哪些项目(首先并不总是一个好的选择)

于 2013-03-20T10:45:02.993 回答
0

您需要使用该Distinct属性

var result = list.DistinctBy(t => t.FirstProp);
于 2013-03-20T10:46:25.973 回答