Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq query to return distinct field values from a list of objects

Tags:

c#

linq

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?

like image 267
patrick Avatar asked Jun 03 '11 18:06

patrick


People also ask

How do I get distinct on a single column in LINQ?

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).

Why distinct is not working in LINQ?

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.


2 Answers

objList.Select(o=>o.typeId).Distinct() 
like image 166
Arsen Mkrtchyan Avatar answered Sep 21 '22 10:09

Arsen Mkrtchyan


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()); 
like image 44
Jon Skeet Avatar answered Sep 20 '22 10:09

Jon Skeet