LINQ Distinct is not that smart when it comes to custom objects. All it does is look at your list and see that it has two different objects (it doesn't care that they have the same values for the member fields). One workaround is to implement the IEquatable interface as shown here.
distinct in Linq to get result based on one field of the table (so do not require a whole duplicated records from table). I know writing basic query using distinct as followed: var query = (from r in table1 orderby r. Text select r).
myList.GroupBy(test => test.id)
.Select(grp => grp.First());
Edit: as getting this IEnumerable<>
into a List<>
seems to be a mystery to many people, you can simply write:
var result = myList.GroupBy(test => test.id)
.Select(grp => grp.First())
.ToList();
But one is often better off working with the IEnumerable
rather than IList
as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList
it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)
The flipside to this advice is that each time you enumerate such an IEnumerable
the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable
or to realize it into a List
, Set
, Dictionary
or whatnot.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With