如何使用 LINQ 执行 SELECT UNIQUE? [英] How can I do SELECT UNIQUE with LINQ?

查看:24
本文介绍了如何使用 LINQ 执行 SELECT UNIQUE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表:

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( "column name" ),即按颜色名称的字母顺序,因此命名属性?

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 specifying 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆