如何在IE#中将IEnumerable转换为自定义类型?

Ton*_*y D 5 c# ienumerable extension-methods casting

我使用扩展方法OrderBy和ThenBy在多个字段上对我的自定义集合进行排序.这种排序不会影响集合,而是返回和IEnumberable.我无法将IEnumerable结果转换为我的自定义集合.反正有没有改变我的集合的顺序或将IEnumerable结果转换为我的自定义集合?

Ken*_* K. 6

如果您的集合类型实现IList<T>(能够实现Add()),您可以编写扩展方法:

public static Extensions
{
    public static TColl ToTypedCollection<TColl, T>(this IEnumerable ien)
        where TColl : IList<T>, new()
    {
        TColl collection = new TColl();

        foreach (var item in ien)
        {
            collection.Add((T) item);
        }

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