Reputation: 8219
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?
Upvotes: 1
Views: 357
Reputation: 125650
I don't think there is a way other than just loop over the source collection and call Add
on your MyDbSet
class instance, however it can be hidden in custom extension method:
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;
}
}
Usage:
IList<Items> items = GetItems();
MyDbSet<Items> itemsSet = items.ToMyDbSet();
Upvotes: 1
Reputation: 108830
For collections that support ICollection<T>.Add
you could write a helper method like this:
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;
}
which is used like:
var coll = CreateCollection<MyDbSet<T>, T>(seq);
But personally I'd rather write an AddRange(seq)
extension method and then use it like:
var coll = new MyDbSet<T>();
coll.AddRange(seq);
Upvotes: 1