将字典转换为List<Customer>

3
我有一个 dictionary<String,Object>,我想将它转换为一个 List<Customer>。有没有聪明的方法可以做到这一点?有什么例子吗?谢谢。 编辑 抱歉没有解释清楚。鉴于以下情况,为什么我的结果是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; }
}

1
你的字典中的对象是客户吗?客户由什么组成?听起来你想要一个 LINQ 选择器,但是如果不知道你想在客户中获取什么内容,我们就不知道它应该是什么样子。 - Ben Von Handorf
2个回答

16

肯定有做这件事的方法,但你没有说明“Customer”中包含什么内容,或者字符串、对象和客户之间的关系是什么。

以下是一个例子,可能是合适的(假设你在使用 .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();

(您也可以使用接受 IEnumerable<T>List<T> 构造函数,但我倾向于使用 ToList 扩展方法更易读。)


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

List<Customer> customers = dictionary.Values.OfType<List<Customer>>()
                                            .First();
或者
List<Customer> customers = dictionary.Values.OfType<List<Customer>>()
                                            .FirstOrDefault();

如果没有这样的值,后者会使你得到null;前者会抛出异常。


7
我保证他就像一个声誉黑洞,没有人能逃脱他的引力。 - user1228
5
如果他的TValue可能是顾客,也可能不是(如果他将多种类型保存为值),那么使用OfType<Customer>比使用Cast更合适。 - user1228
我编辑了我的问题并解释了一些内容,并放置了一个测试。但似乎无法得出结果。我做错了什么? - user9969
@devnet247:在你的测试用例中,字典已经将列表本身作为一个值包含在内了。你是想要选择字典中第一个列表吗?还是将所有列表合并在一起? - Jon Skeet
非常感谢,现在一切都正常了。真的很感激您花时间用各种例子来解释。 - user9969
显示剩余2条评论

1

根据您更新的代码,列表中相关对象是 List<Customer>,因此您应该使用 OfType 进行检查。尝试像这样从字典中的所有列表形成单个列表。

var newList = mydictionaryList.Values.OfType<List<Customer>>().SelectMany(list => list).ToList();

否则,您可能会得到一个列表的列表。

嗨, 它在我的简单示例中运行,但在我的真实示例中,我的对象由其他对象组成。贴出所有代码有点复杂,也不确定我能否这样做。简而言之,如果我要按照传统的方式使用foreach,你会怎么做?很遗憾,因为它在发布的示例中有效。现在有点迷失了。 - user9969

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接