Convert Dictionary to <Customer> List
I have dictionary<String,Object>and I want to convert it to List<Customer>
Is there a smart way to do this? Any examples? Thanks
EDITED
Sorry for the incorrect explanation. Given the following, why is my result 0? Please note that I am trying to imitate living situations, and the first key does not make sense and would like to exclude, so that only the clients that I should get. Why is this not working? 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 certain ways to do this, but you didn’t say anything about what's in the client, or about the relationship between the string, the object, and the client.
, ( .NET 3.5 ):
var customers = dictionary.Select(pair => new Customer(pair.Key, pair.Value)
.ToList();
, , , :
var customers = dictionary.Keys.Select(x => new Customer(x))
.ToList();
, , Customer, :
var customers = dictionary.Values.Cast<Customer>().ToList();
, , Customer, , :
var customers = dictionary.Values.OfType<Customer>().ToList();
( List<T>, IEnumerable<T>, ToList .)
EDIT: , , :
List<Customer> customers = dictionary.Values.OfType<List<Customer>>()
.First();
List<Customer> customers = dictionary.Values.OfType<List<Customer>>()
.FirstOrDefault();
null, ; .