7

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

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:

.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?

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.

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

1
  • It's always important to mention any exception messages you get and also what flavor of LINQ you're working with (linq-to-sql I guess?). Commented Sep 20, 2013 at 21:02

3 Answers 3

16

use this

.Select( c => new {c.COURSE_ID, COURSE_TITLE =string.Format("{0} {1}" ,c.CIN ,c.COURSE_TITLE)})
Sign up to request clarification or add additional context in comments.

4 Comments

I think string.Format will only work if the objects are already loaded into memory. I might be wrong, but I'm pretty sure Entity Framework will choke on that, and the posted code looks like it might be EF.
How about for OrderBy?
Simple and Great !
How can I convert this to string array
6

You need to name your anonymous members:

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

1 Comment

This solution worked for me in LINQ to Entities where string.Format would not. Thanks!
3

Write your Select like this:

.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_ID C# is smart enough to generate a member called COURSE_ID in the anonymous type. For the expression c.CIN + " " + c.COURSE_TITLE it cannot.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.