0

I am using LINQ to Entites in my WindowsForm application.

I am trying to populate a Lisbox with the result of a query:

So my datasource is a List where User is a table in my database and a EntityType in my model.

The problem is I want the Displaymember to bea concat of 3 different Columns. (User.Firstname + " " + user.LastName + " - " + user.userCode)

and ValueMember to be user.ID;

I could just create a struct of a userItem with the 4 items, iterate through the list of User's and add them to another List. But this seems like double processing.

Michael
  • 8,229
  • 20
  • 61
  • 113

2 Answers2

3

You can extend the Entity in the partial class with a custom property like this:

public partial class User
{
    public string Description
    {
        get
        {
             return string.Format("{0} {1} - {2}", FirstName, LastName, UserCode);
        }
    }
}

If you don't want to add the property you can also use a Linq Projection to create a custom list with the computed property:

var listdata = (from u in Users
                select new
                {
                   Description = string.Format("{0} {1} - {2}", u.FirstName, u.LastName, u.UserCode).
                   Id = u.Id;    
                }.ToList();

Then you can bind listdata to your listbox.

Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103
  • I ended up extending my entity as you suggested. is String.format more efficent than just " " + " " + - "" ? or you just prefer it for cosmetic reasons – Michael Jan 11 '12 at 03:16
  • I always thought that string.Format was more efficient, that's why I used it in this example but when I searched for a reference I came across http://stackoverflow.com/questions/16432/c-sharp-string-output-format-or-concat and it appears that concatenation is faster! – Wouter de Kort Jan 11 '12 at 13:55
2

Why don't you just create a property in your model which returns the concatenated value from three columns/properties. Then set the DisplayMemeber equal to that property

Another way could be to add a Computed Columns in your table. Combine the value of rest of the columns through expression

Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
  • I would shoot anyone who added a computed column to the database for what is essentially a display property. Just saying. Not a good place to put it. – slugster Jan 10 '12 at 07:24
  • I wouldnt put it on hte Database, but perhapes in the LINQ model it is acceptable? – Michael Jan 11 '12 at 03:06