将IEnumerable <T>转换为用户类型的更好方法

Nev*_*vyn 10 .net c# linq

我有一个自定义集合类型,定义如下:

public abstract class RigCollectionBase<T> : Collection<T>, IEnumerable<T>, INotifyPropertyChanged, IBindingList, ICancelAddNew where T : BusinessObjectBase, new()
Run Code Online (Sandbox Code Playgroud)

注意:这是基类,有20个左右的子类实现如下:

public class MyCollection : RigCollectionBase<MyObject>
Run Code Online (Sandbox Code Playgroud)

我们在代码中使用了很多Linq,正如您可能知道的那样,Linq函数返回IEnumerable<T>.我正在寻找的,是一个容易和简单的方式回到MyCollectionIEumberable<MyObject>.不允许施法,我得到例外情况"无法施放..."

这是我想出的答案,它确实有效,但它似乎有点笨重而且......过于复杂.也许不是,但我想我会在那里看看是否有更好的方法.

public static class Extension
{
    /// <summary>
    /// Turn your IEnumerable into a RigCollection
    /// </summary>
    /// <typeparam name="T">The Collection type</typeparam>
    /// <typeparam name="U">The Type of the object in the collection</typeparam>
    /// <param name="col"></param>
    /// <returns></returns>
    public static T MakeRigCollection<T, U> (this IEnumerable<U> col) where T : RigCollectionBase<U>, new() where U : BusinessObjectBase, new()
    {
        T retCol = new T();

        foreach (U myObj in col)
            retCol.Add(myObj);

        return retCol;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想,我真正想要的是这个.有没有办法实现基类,以便我可以使用一个简单的转换从IEnumerable转到MyCollection ...

var LinqResult = oldCol.Where(a=> someCondition);
MyCollection newCol = (MyCollection)LinqResult;
Run Code Online (Sandbox Code Playgroud)

不,上面的代码不起作用,我实际上不是100%肯定为什么......但事实并非如此.感觉就像我没有看到一些非常明显的步骤....

usr*_*usr 4

你的方法MakeRigCollection基本上是正确的方法。这是一个使用起来稍微冗长但实现起来更简单的变体:

TCollection MakeRigCollectionSimple<TCollection, TItem>(
    this IEnumerable<TItem> items, TCollection collection)
    where TCollection : ICollection<TItem>
{
        foreach (var myObj in items)
            collection.Add(myObj);
        return collection;
}
Run Code Online (Sandbox Code Playgroud)

我希望我做对了。你像这样使用它:

MakeRigCollectionSimple(items, new MyCollection());
Run Code Online (Sandbox Code Playgroud)

或者

items.MakeRigCollectionSimple(new MyCollection());
Run Code Online (Sandbox Code Playgroud)

现在你需要填写第二个参数,但作为交换,我们能够摆脱所有疯狂的泛型东西。只剩下简单的泛型了。类型推断完全发挥作用。此外,这适用于所有集合类型,而不仅仅是 RigCollections。