且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将IEnumerable转换为C#中的自定义类型?

更新时间:2022-11-18 22:04:18

IList< T> (为了能够 Add())可以写一个扩展方法: p>

If your collection type implements IList<T> (to be able to Add() to it) you could write an extension method:

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;
    }
}