简体   繁体   English

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

[英]Select the first records for a property with linq

I have a class 我有一堂课

class Test
{
    public string FirstProp { get; set; }
    public string SecondProp { get; set; }
    public string ThirdProp { get; set; }
}

and a list of objects 和对象列表

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" },
};

I need to select the first FirstProp records: 我需要选择第一个FirstProp记录:

FirstProp = "xxx", SecondProp = "x2", ThirdProp = "x3"
FirstProp = "yyy", SecondProp = "y2", ThirdProp = "y3"

How to do it in the best way using linq ? 如何使用linq以最佳方式做到这一点?

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

 list.GroupBy(x => x.FirstProp).Select(g => g.First())
list.GroupBy (l => l.FirstProp).Select (l => l.First ())

可以在这里使用,但您需要确定每个组中需要拿的是什么(首先并不总是一个好选择)

您需要使用Distinct属性

var result = list.DistinctBy(t => t.FirstProp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM