将字典转换为List <Customer>

use*_*969 3 c#

我有一个dictionary<String,Object>,我想把它转换为a List<Customer> 有一个聪明的方法吗?任何例子?谢谢

EDITED

很抱歉没有正确解释.鉴于以下原因,为什么我的结果为0?请注意我试图模拟一个现场情况,第一个键没有意义,并希望排除所以只有我应该得到的客户.为什么不起作用?谢谢你的任何建议

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; }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 16

必然会有这样做的方法,但你没有说过客户的内容,或者字符串,对象和客户之间的关系.

这是一个可能合适的示例(假设您使用的是.NET 3.5或更高版本):

var customers = dictionary.Select(pair => new Customer(pair.Key, pair.Value)
                          .ToList();
Run Code Online (Sandbox Code Playgroud)

或者您可能只对密钥感兴趣,密钥应该是客户的名称:

var customers = dictionary.Keys.Select(x => new Customer(x))
                               .ToList();
Run Code Online (Sandbox Code Playgroud)

或者也许每个值已经是a Customer,但你需要强制转换:

var customers = dictionary.Values.Cast<Customer>().ToList();
Run Code Online (Sandbox Code Playgroud)

或者,您的某些值可能是Customer值,但其他值则不是,您想跳过这些值:

var customers = dictionary.Values.OfType<Customer>().ToList();
Run Code Online (Sandbox Code Playgroud)

(您也可以使用的构造函数List<T>这需要一个IEnumerable<T>,但我倾向于找ToList扩展方法更具可读性.)


编辑:好的,现在我们知道要求,选项是:

List<Customer> customers = dictionary.Values.OfType<List<Customer>>()
                                            .First();
Run Code Online (Sandbox Code Playgroud)

要么

List<Customer> customers = dictionary.Values.OfType<List<Customer>>()
                                            .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

null如果没有这样的价值观,后者会留给你; 前者将抛出异常.

  • 我发誓他就像一个代表黑洞.没有人可以逃脱他的引力. (7认同)
  • 此外,如果他的TValue可能是也可能不是客户(如果他保留多个类型作为价值),那么使用OfType <Customer>比使用Cast更合适. (5认同)