Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

like image 978
PaulH Avatar asked Mar 08 '11 17:03

PaulH


People also ask

Is a dictionary an IEnumerable?

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.

Why to use IEnumerable instead of list?

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.

When to use IEnumerable?

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.


1 Answers

return source.ToDictionary(item => item.ID, item => item.Text);
like image 63
Domenic Avatar answered Oct 23 '22 03:10

Domenic