Alex Kovanev
Alex Kovanev

Reputation: 1888

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 = "xxx", SecondProp = "x2", ThirdProp = "x3"
FirstProp = "yyy", SecondProp = "y2", ThirdProp = "y3"

How to do it in the best way using linq?

Upvotes: 0

Views: 1621

Answers (3)

Toon Casteele
Toon Casteele

Reputation: 2579

You need to use the Distinct property

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

Upvotes: 0

jezzarax
jezzarax

Reputation: 413

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

will work here but you need to determine what item from each group you need to take (First is not always a good choice)

Upvotes: 3

cuongle
cuongle

Reputation: 75296

You can use GroupBy on the property FirstProp, and then do get First:

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

Upvotes: 8

Related Questions