Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do SELECT UNIQUE with LINQ?

I have a list like this:

Red Red Brown Yellow Green Green Brown Red Orange 

I am trying to do a SELECT UNIQUE with LINQ, i.e. I want

Red Brown Yellow Green Orange  var uniqueColors = from dbo in database.MainTable                    where dbo.Property == true                    select dbo.Color.Name; 

I then changed this to

var uniqueColors = from dbo in database.MainTable                    where dbo.Property == true                    select dbo.Color.Name.Distinct(); 

with no success. The first select gets ALL the colors, so how do I modify it to only get the unique values?

If there is a better way of structuring this query, more than happy to go that route.

How do I go about editing it so I can have .OrderBy( "column name" ) i.e. alphabetically by color name, so name property?

I keep getting a message:

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly.

like image 956
baron Avatar asked Aug 19 '10 06:08

baron


People also ask

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.

How do you select unique data?

The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.


2 Answers

The Distinct() is going to mess up the ordering, so you'll have to the sorting after that.

var uniqueColors =                 (from dbo in database.MainTable                   where dbo.Property == true                   select dbo.Color.Name).Distinct().OrderBy(name=>name); 
like image 169
James Curran Avatar answered Oct 19 '22 14:10

James Curran


var uniqueColors = (from dbo in database.MainTable                      where dbo.Property == true                     select dbo.Color.Name).Distinct(); 
like image 30
jwendl Avatar answered Oct 19 '22 13:10

jwendl