Reputation: 1888
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
Reputation: 2579
You need to use the Distinct
property
var result = list.DistinctBy(t => t.FirstProp);
Upvotes: 0
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