1

Lets say i have collection IList<Items> items = GetItems(); I want to convert that collection in to collection of MyDbSet<Items>

MyDbSet declared like that: public class MyDbSet<T> : IDbSet<T> where T : class

How can i do that with the less amount of code, possibly it is better to go with linq?

4

2 回答 2

1

我认为除了循环源集合并调用Add您的MyDbSet类实例之外没有其他方法,但是它可以隐藏在自定义扩展方法中:

public static class MyEnumerable
{
    public static MyDbSet<T> ToMyDbSet<T>(this IEnumerable<T> source)
        where T : class
    {
        var collection = new MyDbSet<T>();

        foreach (var item in source)
            collection.Add(item);

        return collection;
    }
}

用法:

IList<Items> items = GetItems();

MyDbSet<Items> itemsSet = items.ToMyDbSet();
于 2013-04-13T13:50:49.780 回答
1

对于支持的集合,ICollection<T>.Add您可以编写一个这样的辅助方法:

public static TCollection CreateCollection<TCollection,TElement>(IEnumerable<TElement> seq)
    where TCollection:ICollection<TElement>, new
{
    var coll=new TCollection();
    foreach(var element in seq)
      coll.Add(element);
    return coll;
}

使用如下:

var coll = CreateCollection<MyDbSet<T>, T>(seq);

但就我个人而言,我宁愿写一个AddRange(seq)扩展方法,然后像这样使用它:

var coll = new MyDbSet<T>();
coll.AddRange(seq);
于 2013-04-13T13:46:12.017 回答