[英]filling a Dictionary<> with an IEnumerable<> source
I have a VS2008 C# .NET 3.5 application where I would like to create a hashtable of objects given an IEnumerable list of those objects. 我有一个VS2008 C#.NET 3.5应用程序,我想在给定这些对象的IEnumerable列表的情况下创建对象的哈希表。
Basically, it looks like this: 基本上,它看起来像这样:
public class MyCollection<T> : IEnumerable<T>
where T: IMyData, new()
{
private IDictionary<int, string> collection_ = new Dictionary<int, string>();
// ...
public void Add(T item)
{
collection_.Add(item.ID, item.Text);
}
public static MyCollection<T> Create(IEnumerable<T> source)
{
MyCollection<T> c = new MyCollection<T>();
foreach(T item in source)
{
c.Add(item);
}
return c;
}
}
This works, but I wonder if there isn't a better way of copying from one IEnumerable source to another. 这有效,但我想知道是否没有更好的方法从一个IEnumerable源复制到另一个。 Any suggestions? 有什么建议?
Thanks, PaulH 谢谢,PaulH
return source.ToDictionary(item => item.ID, item => item.Text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.