Converting a dictionary to a List<Customer>
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):
var customers = dictionary.Select(pair => new Customer(pair.Key, pair.Value)
.ToList();
Or maybe you're only interested in the keys, which should be the names of the customers:
var customers = dictionary.Keys.Select(x => new Customer(x))
.ToList();
Or maybe each value is already a Customer
, but you need to cast:
var customers = dictionary.Values.Cast<Customer>().ToList();
Or maybe some of your values are Customer
values but others aren't, and you want to skip those ones:
var customers = dictionary.Values.OfType<Customer>().ToList();
(You can also use the constructor of List<T>
which takes an IEnumerable<T>
but I tend to find the ToList
extension method more readable.)
EDIT: Okay, now we know the requirements, the options are:
List<Customer> customers = dictionary.Values.OfType<List<Customer>>()
.First();
or
List<Customer> customers = dictionary.Values.OfType<List<Customer>>()
.FirstOrDefault();
The latter will leave you with null
if there are no such values; the former will throw an exception.
Given your updated code, the relevant object in your list is a List<Customer>
, so that's what you should check for with OfType. Try soemthing like this to form a single list from all the lists in your dictionary.
var newList = mydictionaryList.Values.OfType<List<Customer>>().SelectMany(list => list).ToList();
Otherwise, you could get a list of lists.
精彩评论