如何使用 LINQ 执行 SELECT UNIQUE?

我有一个这样的清单:

Red
Red
Brown
Yellow
Green
Green
Brown
Red
Orange

我正在尝试用 LINQ 做一个 SELECT UNIQUE,也就是说,我想

Red
Brown
Yellow
Green
Orange


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

然后我把它改成

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

没有成功。第一个 select得到所有的颜色,那么我如何修改它只得到唯一的值?

如果有一个更好的方法来构造这个查询,我会非常乐意走这条路。

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

我一直收到一条信息:

无法从用法推断类型参数。请尝试显式指定类型参数。

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

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

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);
var unique = (from n in test group n by n into g where g.Count()==1 select g.Key.ToString());