How can I do SELECT UNIQUE with LINQ?

2019-01-14 04:50发布

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 specificying the type arguments explicitly.

3条回答
走好不送
2楼-- · 2019-01-14 05:23
var uniqueColors = (from dbo in database.MainTable 
                    where dbo.Property == true
                    select dbo.Color.Name).Distinct();
查看更多
劳资没心,怎么记你
3楼-- · 2019-01-14 05:42

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);
查看更多
成全新的幸福
4楼-- · 2019-01-14 05:44

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();
查看更多
登录 后发表回答