class obj { int typeId; //10 types 0-9 string uniqueString; //this is unique }
Assume there is a list with 100 elements of objs, but only 10 unique typeIDs.
Is it possible to write a LINQ query that returns the 10 unique ints from the list of objs?
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).
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.
objList.Select(o=>o.typeId).Distinct()
Assuming you want the full object, but only want to deal with distinctness by typeID
, there's nothing built into LINQ to make this easy. (If you just want the typeID
values, it's easy - project to that with Select
and then use the normal Distinct
call.)
In MoreLINQ we have the DistinctBy
operator which you could use:
var distinct = list.DistinctBy(x => x.typeID);
This only works for LINQ to Objects though.
You can use a grouping or a lookup, it's just somewhat annoying and inefficient:
var distinct = list.GroupBy(x => x.typeID, (key, 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