我希望使用有序的枚举,并将接口用作返回类型,而不是具体类型。我需要返回一组有序的对象。但是,在使用IList实现时,我不能返回IOrderedEnumerable,因为IList不继承IOrderedEnumerable。
在下面的示例中,我有一个视图模型,其中包含一组系列的存储库,实现为系列对象的List,由于它们位于List中,因此已排序。在访问器方法中,我想返回过滤后的系列集,仅返回特定类型的系列对象,同时保留过滤元素中的原始顺序。
编译器告诉我:
我该如何支持这种情况?为什么“List”没有实现“IOrderedEnumerable”?
编辑:澄清我的意图:即使没有显式地指定键,我只是想在接口级别声明我的仓库有一个顺序。 因此,“.ThenBy”等不应添加新的排序,因为已经有一个排序——我的唯一一个排序。:-)。我知道,这样做会忽略“ThenBy”的意图。
/// <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
}
编译器告诉我:
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?) ...
我该如何支持这种情况?为什么“List”没有实现“IOrderedEnumerable”?
编辑:澄清我的意图:即使没有显式地指定键,我只是想在接口级别声明我的仓库有一个顺序。 因此,“.ThenBy”等不应添加新的排序,因为已经有一个排序——我的唯一一个排序。:-)。我知道,这样做会忽略“ThenBy”的意图。