Mar*_*cel 11 c# ienumerable ilist types where
我想使用有序的枚举,并使用接口作为返回类型而不是具体类型.我需要返回一组有序的对象.但是,当使用IList<T>实现时,我无法返回IOrderedEnumerable<T>,因为IList<T>不继承IOrderedEnumerable<T>.
在下面的示例中,我有一个视图模型,其中包含一个系列的存储库,实现为List<T>一系列对象,因为它们位于一个List<T>有序的对象中.我是一个访问器方法,我想返回一个系列的过滤集,其中只返回特定类型的系列对象,同时保持过滤元素之间的原始顺序.
/// <summary>
/// Represents the view model for this module.
/// </summary>
public class ViewModel : AbstractViewModel
{
/// <summary>
/// Gets the series repository.
/// </summary>
/// <value>The series repository.</value>
public IList<ISeries> SeriesRepository { get; private set; }
//...
}
//8<-----------------------------
/// <summary>
/// Gets the series of the specified type.
/// </summary>
public IOrderedEnumerable<T> Series<T>() where T : ISeries
{
return ViewModel.SeriesRepository.OfType<T>(); //compiler ERROR
}
Run Code Online (Sandbox Code Playgroud)
编译器告诉我:
Error 14 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<T>' to 'System.Linq.IOrderedEnumerable<T>'. An explicit conversion exists (are you missing a cast?) ...
Run Code Online (Sandbox Code Playgroud)
我该如何支持这种情况?为什么List没有实现IOrderedEnumerable?
编辑:澄清我的意图:我只是想在接口级别声明我的存储库有一个订单,即使它没有由一个键明确指定.因此,.ThenByet.al.不应该添加新订单,因为已经存在一个 - 我自己的一个且只有一个.:-).我知道,就像这样,我想念的意图.ThenBy.
Jon*_*eet 15
怎么可以 List<T>实现IOrderedEnumerable<T>?它必须提供一种创建后续订购的方式......这甚至意味着什么?
考虑一下:
var names = new List<string> { "Jon", "Holly", "Tom", "Robin", "William" };
var ordered = names.ThenBy(x => x.Length);
Run Code Online (Sandbox Code Playgroud)
那有什么意思?没有主要的排序顺序(如果我使用的那样names.OrderBy(x => x)),因此不可能强加二级排序.
我建议你尝试创建自己的实现IOrderedEnumerable<T>基于一个List<T>-因为你试图实现CreateOrderedEnumerable的方法,我想你会看到为什么它是不恰当的.您可能会发现我的Edulinq博客文章IOrderedEnumerable<T>很有用.
Dan*_*rth 10
那么,你就错了:List<T>是不是由一个特定的键进行排序.列表中的元素按照您放入的顺序排列.这就是为什么List<T>不实现的原因IOrderedEnumerable<T>.
只需返回以下内容:
ViewModel.SeriesRepository.OfType<T>().OrderBy(<your order predicate>);
Run Code Online (Sandbox Code Playgroud)