C# 选择一列,按另一列排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19011873/
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-08-10 13:54:00  来源:igfitidea点击:

Select one column, order by another

c#linqlinq-to-sqlsql-order-by

提问by Daniel B

I'm using LINQ to SQL to select from a database. I want to select one column that consists of values that are String, but order by another column that contains a "priority"-value that is an int.

我正在使用 LINQ to SQL 从数据库中进行选择。我想选择一个包含 的值的列String,但按包含“优先级”值的另一列排序,该值是int.

This is what my LINQ statement looks like right now:

这就是我的 LINQ 语句现在的样子:

var query = from vk in db.Valdkurs
            where vk.pnr == pnr
            select vk.kursnamn.OrderByDescending(x => vk.prioritet);

On the third line of code a NotSupportedExceptionis thrown with the exception message

在第三行代码NotSupportedException中抛出异常消息

Sequence operators not supported for type 'System.String'

类型“System.String”不支持序列运算符

I have come to the conclusion that it is probably because of the

我得出的结论是,这可能是因为

vk.kursnamn.OrderByDescending(x => vk.prioritet);

where vk.Kursnamnis of Stringtype.

哪里vk.KursnamnString类型。

How can I select the vk.Kursnamnand order them by the vk.Priority?

我如何选择vk.Kursnamn和订购它们vk.Priority

采纳答案by dasblinkenlight

You need to first order, and then select, like this:

您需要先订购,然后选择,如下所示:

var query = db.Valdkurs
    .Where(vk=> vk.pnr == pnr)   // Filter
    .OrderBy(vk => vk.prioritet) // prioritet is still here - order by it
    .Select(vk => vk.kursnamn);  // Now grab the kursnamn

Otherwise, LINQ thinks that you are trying to order the characters of the string, which is not a supported operation.

否则,LINQ 会认为您正在尝试对 的字符进行排序string,这是不支持的操作。

回答by David

I'm not sure of the LINQ syntax, but essentially what you're trying to do is:

我不确定 LINQ 语法,但基本上你想要做的是:

var query = db.Valdkurs
              .Where(vk=> vk.pnr == pnr)
              .OrderByDescending(vk => vk.prioritet)
              .Select(vk => vk.kursnamn);

You can chain these together in all sorts of ways. Essentially each one modifies the collection and returns the modified collection. (Or at least they will evaluate that way when they're executed, which happens when you call .ToList()for example.)

您可以通过各种方式将这些链接在一起。本质上,每个人都会修改集合并返回修改后的集合。(或者至少他们会在执行时以这种方式进行评估,.ToList()例如,当您调用时就会发生这种情况。)

回答by Reed Copsey

You would rewrite this as:

您可以将其重写为:

var query = from vk in db.Valdkurs 
            where vk.pnr == pnr 
            orderby vk.prioritet descending
            select vk.kursnamn;

回答by hadi.sh

Try this:

尝试这个:

int id =Convert.ToInt32(db.Table.Single(x => x.Id == id_factor).Id);