我正在使用扩展方法 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/