How can I do SELECT UNIQUE with LINQ?

SqlVisual StudioLinqSelectUnique

Sql Problem Overview


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.

Sql Solutions


Solution 1 - Sql

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

Solution 2 - Sql

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

Solution 3 - Sql

Using query comprehension syntax you could achieve the orderby as follows:

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

Solution 4 - Sql

var unique = (from n in test group n by n into g where g.Count()==1 select g.Key.ToString());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbaronView Question on Stackoverflow
Solution 1 - SqlJames CurranView Answer on Stackoverflow
Solution 2 - SqljwendlView Answer on Stackoverflow
Solution 3 - SqlcordialgermView Answer on Stackoverflow
Solution 4 - SqlpierreView Answer on Stackoverflow