Coder Perfect

How can I use LINQ to do SELECT UNIQUE?

Problem

I have a list that looks like this:

Red
Red
Brown
Yellow
Green
Green
Brown
Red
Orange

I’m attempting to perform a SELECT UNIQUE with LINQ.

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

but without success How can I make the initial choice only receive the unique values instead of all the colors?

I’d be happy to go that route if there’s a better way to structure this query.

What should I do to change it so that I can have? So name property? OrderBy(“column name”), i.e. alphabetically by color name?

I keep getting the following message:

Asked by baron

Solution #1

The ordering will be messed up by Distinct(), so you’ll have to sort after that.

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

Answered by James Curran

Solution #2

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

Answered by jwendl

Solution #3

You might get the orderby using query comprehension syntax as follows:

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

Answered by cordialgerm

Solution #4

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

Answered by pierre

Post is based on https://stackoverflow.com/questions/3519165/how-can-i-do-select-unique-with-linq