luke_t
luke_t

Reputation: 2985

LINQ query results into List

I have a class called Name with one property.

public class Name
{
    public string comboName { get; set; }
}

I'm attempting to run a LINQ query to return all FullName, and then create an instance of the Name class for each, assigning FullName to the property comboName. The instances are added to a List, and then I want List values to be added to ComboBox1 drop down values. Below is the code I've written so far.

void ComboBox1_Loaded(object sender, RoutedEventArgs e)
{
    GiftIdeasDataContext dc = new GiftIdeasDataContext();

    var qry = from r in dc.Recipients
                select new Name()
                {
                    comboName = r.FullName
                };

    List<Name> lst = qry.ToList();
    ComboBox1.ItemsSource = lst;
}

Issue: When the code is executed the ComboBox1 drop down only shows the string 'myMemory.Name' 9 times (the number of names which are in the Recipient table). Should I just create a list and assign string values to the list instead of using a class?

I've only been using the console window with c# up to now, this is my first project using WPF, so any help is appreciated.

Upvotes: 3

Views: 3088

Answers (3)

sujith karivelil
sujith karivelil

Reputation: 29036

List<Name> lst= from r in dc.Recipients
                select new Name()
                {
                  comboName = r.FullName
                }.ToList<Name>();

or you can convert like the following :

List<Name> lst = (List<Name>)qry.ToList();

Upvotes: 1

FlyingFoX
FlyingFoX

Reputation: 3509

The ComboBox needs to know how you want instances of your Name class displayed. As you didn't explicitly tell it, it uses Name.ToString() to display your Name instances.

You can explicitly tell the ComboBox how to display instances of your Name class through setting ComboBox1.DisplayMemberPath to comboName.

Upvotes: 2

Kevin P.
Kevin P.

Reputation: 401

var lst = dc.Recipients.Select(r => new Name{ comboName = r.FullName }).ToList();

Upvotes: 0

Related Questions