C# 使用 WHERE 子句在 Linq 中选择 AS

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

SELECT AS in Linq with WHERE clause

c#linq

提问by enigma20

I am trying to populate a drop down list with a Linq query. However, I need to have FirstName and Surname as one field. Concatenating in the DDL.DataTextFieldreturns a field not found error.

我正在尝试使用 Linq 查询填充下拉列表。但是,我需要将名字和姓氏作为一个字段。连接DDL.DataTextField返回一个字段未找到错误。

SQL would be something like this:

SQL 将是这样的:

SELECT (FirstName + SPACE + Surname) AS FullName FROM Table WHERE ID=1

Current Linq:

当前 Linq:

public IList<mytable> GetNames(int p_ID)
{
    return db.mytable.Where(c => c.ID_fk == p_ID).ToList();
}

采纳答案by Daniel Hilgarth

You can use this, if you onlyneed the full name:

如果您需要全名,则可以使用它:

public IList<string> GetNames(int p_ID)
{
    return db.mytable.Where(c => c.ID_fk == p_ID)
                     .Select(x => x.FirstName + " " + x.Surname)
                     .ToList();
}

回答by stefano m

you could try this:

你可以试试这个:

return db.mytable.Where(c => c.ID_fk == p_ID).Select(c=>c.FirstName + " " + c.Surname). ToList();

so you have a list of strings

所以你有一个字符串列表

回答by Aghilas Yakoub

You can try with

你可以试试

return db.mytable.Where(a => a.ID_fk==p_ID)
                  .Select(a => a.FirstName + "-" + a.Surname)
                  .ToList();