简体   繁体   中英

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

return source.ToDictionary(item => item.ID, item => item.Text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM