如何使用 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" )
即按颜色名称的字母顺序排列,即 name 属性?
我不断收到一条消息:
无法从用法推断类型参数。尝试显式指定类型参数。
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 specifying the type arguments explicitly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Distinct()
会打乱排序,因此您必须在此之后进行排序。The
Distinct()
is going to mess up the ordering, so you'll have to the sorting after that.使用查询理解语法,您可以实现 orderby,如下所示:
Using query comprehension syntax you could achieve the orderby as follows: