I have a class list of class
public class LinqTest
{
public int id { get; set; }
public string value { get; set; }
}
List<LinqTest> myList = new List<LinqTest>();
myList.Add(new LinqTest() { id = 1, value = "a" });
myList.Add(new LinqTest() { id = 1, value = "b" });
myList.Add(new LinqTest() { id = 2, value = "c" });
I need to select only the distinct id's from that list. ie, my resultant list should only contain
[{id=1,value="a"},{ id = 2, value = "c" }]
How can I do this with linq?
Edit
Input,
id value
1 a
1 b
2 c
3 d
3 e
Out put should be,
id value
1 a
2 c
3 d
ie, if there is a repetition of id
, result should take the first occurrence only.
Using morelinq you can use DistinctBy
:
myList.DistinctBy(x => x.id);
Otherwise, you can use a group:
myList.GroupBy(x => x.id)
.Select(g => g.First());
You should override Equals
and GetHashCode
meaningfully, in this case to compare the ID:
public class LinqTest
{
public int id { get; set; }
public string value { get; set; }
public override bool Equals(object obj)
{
LinqTest obj2 = obj as LinqTest;
if (obj2 == null) return false;
return id == obj2.id;
}
public override int GetHashCode()
{
return id;
}
}
Now you can use Distinct
:
List<LinqTest> uniqueIDs = myList.Distinct().ToList();
myList.GroupBy(i => i.id).Select(group => group.First())
Source: Stackoverflow.com