如何使用LINQ进行SELECT UNIQUE? [英] How can I do SELECT UNIQUE with LINQ?
问题描述
我有一个这样的列表:
Red
Red
Brown
Yellow
Green
Green
Brown
Red
Orange
我正在尝试使用LINQ做一个SELECT UNIQUE,即我想要
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;
然后我将其更改为
var uniqueColors = from dbo in database.MainTable
where dbo.Property == true
select dbo.Color.Name.Distinct();
没有成功.第一个select
获得所有颜色,那么如何修改它以仅获得唯一的值?
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.
如何进行编辑,以便可以使用.OrderBy(列名称"),即按颜色名称的字母顺序排列,即名称属性?
How do I go about editing it so I can have .OrderBy( "column name" ) i.e. alphabetically by color name, so name property?
我不断收到一条消息:
不能从用法中推断出类型参数.尝试显式指定类型参数.
The type arguments cannot be inferred from the usage. Try specificying the type arguments explicitly.
推荐答案
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);
这篇关于如何使用LINQ进行SELECT UNIQUE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!