C# 在 LINQ select 中连接两个字段

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

Concatenating two fields in LINQ select

c#linqconcatenation

提问by Kevin

I have a dropdownlist, ddCourse, that I'm populating with the following LINQ query:

我有一个下拉列表 ddCourse,我正在使用以下 LINQ 查询填充它:

var db = new DataClasses1DataContext();
ddCourse.DisplayMember = "COURSE_TITLE";
ddCourse.ValueMember = "COURSE_ID";
ddCourse.DataSource = db.COURSE_MASTERs.OrderBy(c => c.COURSE_TITLE)
                                       .Select(c => new { c.COURSE_ID, c.COURSE_TITLE })
                                       .ToList();

There's another field, though, that I'd like to concatenate to the COURSE_TITLE field in my selection. So, I'd like my selection to look like:

但是,我想将另一个字段连接到我选择的 COURSE_TITLE 字段。所以,我希望我的选择看起来像:

.Select( c => new {c.COURSE_ID, c.CIN + " " + c.COURSE_TITLE})

The only problem is that this, apparently, isn't how it's done. I'm basically wanting to join c.CIN with c.COURSE_TITLE (and have a space in the middle). Can someone offer me some pointers on how to accomplish this?

唯一的问题是,这显然不是它的做法。我基本上想将 c.CIN 与 c.COURSE_TITLE 一起加入(并在中间留一个空格)。有人可以为我提供一些有关如何完成此操作的指示吗?

The reason I want to do this is that, right now, the only thing appearing in the dropdownlist is the course title. I'd like to have the course ID number (CIN) concatenated to it when it displays.

我想这样做的原因是,现在,下拉列表中唯一出现的是课程标题​​。我希望在显示时将课程 ID 号 (CIN) 连接到它。

EDIT: For clarification, I'm using Linq-to-SQL.

编辑:为了澄清起见,我使用的是 Linq-to-SQL。

采纳答案by Thilina H

use this

用这个

.Select( c => new {c.COURSE_ID, COURSE_TITLE =string.Format("{0} {1}" ,c.CIN ,c.COURSE_TITLE)})

回答by Cristian Lupascu

Write your Selectlike this:

Select像这样写你的:

.Select( c => new {c.COURSE_ID, COURSE_TITLE = c.CIN + " " + c.COURSE_TITLE})

Anonymous types need to have their column names specified, in case they cannot be inferred.

匿名类型需要指定其列名,以防无法推断。

For c.COURSE_IDC# is smart enough to generate a member called COURSE_IDin the anonymous type. For the expression c.CIN + " " + c.COURSE_TITLEit cannot.

因为c.COURSE_IDC# 足够聪明,可以生成COURSE_ID匿名类型中调用的成员。对于表达式,c.CIN + " " + c.COURSE_TITLE它不能。

回答by SouthShoreAK

You need to name your anonymous members:

您需要命名您的匿名成员

.Select( c => new {COURSE_ID = c.COURSE_ID, COURSE_TITLE = c.CIN + " " + c.COURSE_TITLE})