首页 / C# / c# – 将字典转换为List
c# – 将字典转换为List
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 将字典转换为List,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1824字,纯文字阅读大概需要3分钟。
内容图文
![c# – 将字典转换为List](/upload/InfoBanner/zyjiaocheng/764/bc18d692e9674970b12f72c221ed0734.jpg)
我有一个字典< String,Object>我想将它转换为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; }
}
解决方法:
必然会有这样做的方法,但你没有说过客户的内容,或者字符串,对象和客户之间的关系.
这是一个可能合适的示例(假设您使用的是.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();
或者每个值都可能是客户,但您需要投射:
var customers = dictionary.Values.Cast<Customer>().ToList();
或者您的某些值可能是客户值,但其他值不是,您想跳过这些值:
var customers = dictionary.Values.OfType<Customer>().ToList();
(你也可以使用List< T>的构造函数,它采用IEnumerable< T>但我倾向于发现ToList扩展方法更具可读性.)
编辑:好的,现在我们知道要求,选项是:
List<Customer> customers = dictionary.Values.OfType<List<Customer>>()
.First();
要么
List<Customer> customers = dictionary.Values.OfType<List<Customer>>()
.FirstOrDefault();
如果没有这样的值,后者会给你null;前者将抛出异常.
内容总结
以上是互联网集市为您收集整理的c# – 将字典转换为List全部内容,希望文章能够帮你解决c# – 将字典转换为List所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。