Reputation: 7843
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.
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. Any suggestions?
Thanks, PaulH
Upvotes: 9
Views: 5557
Reputation: 112807
return source.ToDictionary(item => item.ID, item => item.Text);
Upvotes: 21