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
Dictionary is a hash-map datastructure that implements the IEnumerable interface, hence it have all the methods and properties that the IEnumerable interface requires its implementations to have, making it possible to Enumerate the Dictionary structure.
IEnumerable is best to query data from in-memory collections like List, Array etc. IEnumerable doesn't support add or remove items from the list. Using IEnumerable we can find out the no of elements in the collection after iterating the collection. IEnumerable supports deferred execution.
IEnumerable is best to query data from in-memory collections like List, Array, etc. While query data from a database, IEnumerable execute a select query on the server side, load data in-memory on a client-side and then filter data. IEnumerable is suitable for LINQ to Object and LINQ to XML queries.
return source.ToDictionary(item => item.ID, item => item.Text);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With