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

标签 c# extension-methods ienumerable casting

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

最佳答案

如果您的集合类型实现了 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;
    }
}

关于c# - 如何在 C# 中将 IEnumerable 转换为自定义类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1121938/

相关文章:

c# - mono c# strange Address already in use 错误

c# - IEnumerable 与 Ilist - IsNullOrEmpty 扩展方法

c# - 将字典转换为两个列表的最佳方法

c# - 在没有 foreach 循环的情况下使用 IEnumerable

c# - 如何使用正则表达式制作如下所示的模式?

c# - 创建实体时发现重复记录错误

c# - 以编程方式删除克隆存储库的目录

java - Scout Eclipse 表格页面模板

visual-studio-2008 - 可枚举的 LINQ 扩展隐藏在字符串上......为什么以及如何?

作为接口(interface)实现的 C# 扩展方法