SQL 如何使用 LINQ 执行 SELECT UNIQUE?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3519165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:15:33  来源:igfitidea点击:

How can I do SELECT UNIQUE with LINQ?

sqlvisual-studiolinqselectunique

提问by baron

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

我正在尝试使用 LINQ 执行 SELECT UNIQUE,即我想要

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 selectgets ALL the colors, so how do I modify it to only get the unique values?

没有成功。第一个select获取所有颜色,那么如何修改它以仅获取唯一值?

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?

我该如何编辑它以便我可以拥有 .OrderBy("column name" ) 即按颜色名称的字母顺序,所以名称属性?

I keep getting a message:

我不断收到一条消息:

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

无法从用法推断出类型参数。尝试明确指定类型参数。

回答by James Curran

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

Distinct() 会弄乱排序,因此您必须在此之后进行排序。

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

回答by jwendl

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

回答by cordialgerm

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

使用查询理解语法,您可以按如下方式实现 orderby:

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