none
casting to complex type RRS feed

  • Question

  • I'm trying to figure out how to use the combobox item object collection.  Given the code below, how can I put a term in the "Cast<?>" statement to get my anonymous types back?  Or, is there a completely different way to do it?  Can I explicitly cast 'a'?

    var citiesbox = new ComboBox();
    ComboBox.ObjectCollection objects_to_store = new ComboBox.ObjectCollection(citiesbox);
    objects_to_store.Add(new { cityid = 1, cityname = "Eugene" });
    objects_to_store.Add(new { cityid = 2, cityname = "Portland" });
    objects_to_store.Add(new { cityid = 3, cityname = "Salem" });
    
    var citycode_from_db = 2;
    
    citiesbox.SelectedItem = from a in citiesbox.Items.Cast<?>
                 where a.cityid = citycode_from_db
                 select a;
    
    -Ethan Nelson

    Thursday, October 14, 2010 3:46 PM

Answers

  • You shouldn't use an anonymous type here.  Instead, make a custom class that contains your two items.  This will allow you to cast the item back out of the collection.

     

    class City
    {
      public string Name { get; private set; }
      public int Id { get; private set; }
      public City(int id, string name)
      {
        this.Id = id;
        this.Name = name;
      }
    }
    
    
    var citiesbox = new ComboBox();
    ComboBox.ObjectCollection objects_to_store = new ComboBox.ObjectCollection(citiesbox);
    objects_to_store.Add(new City(1,"Eugene"));
    objects_to_store.Add(new City(2, "Portland" ));
    objects_to_store.Add(new City(3, "Salem" ));
    
    var citycode_from_db = 2;
    
    citiesbox.SelectedItem = (from a in citiesbox.Items.Cast<City>
           where a.Id = citycode_from_db
           select a).FirstOrDefault();
    
    


    Reed Copsey, Jr. - http://reedcopsey.com
    • Marked as answer by Ethan Nelson Thursday, October 14, 2010 3:55 PM
    Thursday, October 14, 2010 3:54 PM
    Moderator