I have a dictionary<String,Object> and I want to convert it to a List<Customer>
Is there a clever way of doing that?
Any examples?
Thanks
EDITED
Sorry for not explaining properly.
Given the following why is it my result is 0?
Please note I m trying to emulate a live situation and the first key does not make sense and would like to exclude so only customers i should get.
Why does it not work? Thanks for any suggestions
class Program
{
static void Main(string[] args)
{
List<Customer> oldCustomerList = new List<Customer>
{
new Customer {Name = "Jo1", Surname = "Bloggs1"},
new Customer {Name = "Jo2", Surname = "Bloggs2"},
new Customer {Name = "Jo3", Surname = "Bloggs3"}
};
Dictionary<string,object>mydictionaryList=new Dictionary<string, object>
{
{"SillyKey", "Silly Value"},
{"CustomerKey", oldCustomerList}
};
List<Customer> newCustomerList = mydictionaryList.OfType<Customer>().ToList();
newCustomerList.ForEach(i=>Console.WriteLine("{0} {1}", i.Name, i.Surname));
Console.Read();
}
}
public class Customer
{
public string Name { get; set; }
public string Surname { get; set; }
}
There are bound to be ways of doing it, but you haven’t said anything about what’s in a Customer, or what the relationship between the string, the object and the customer is.
Here’s an example which may be appropriate (assuming you’re using .NET 3.5 or higher):
Or maybe you’re only interested in the keys, which should be the names of the customers:
Or maybe each value is already a
Customer, but you need to cast:Or maybe some of your values are
Customervalues but others aren’t, and you want to skip those ones:(You can also use the constructor of
List<T>which takes anIEnumerable<T>but I tend to find theToListextension method more readable.)EDIT: Okay, now we know the requirements, the options are:
or
The latter will leave you with
nullif there are no such values; the former will throw an exception.