我想使用有序枚举,并使用接口作为返回类型而不是具体类型。我需要返回一组有序的对象。但是,当使用IList<T>
执行我无法返回IOrderedEnumerable<T>
, as IList<T>
不继承IOrderedEnumerable<T>
.
In the example下面我有一个带有系列存储库的视图模型,作为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
}
编译器告诉我:
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?
EDIT:澄清我的意图:我只是想在接口级别声明我的存储库有一个顺序,即使它没有由键明确指定。
因此,.ThenBy
等人。不应添加新订单,因为已经有一个 - 我自己的一个,也是唯一一个。 :-)。我明白了,就像这样,我怀念的意图.ThenBy
.
How could List<T>
实施IOrderedEnumerable<T>
?它必须提供一种创建随后的订购...这是什么意思?
考虑一下:
var names = new List<string> { "Jon", "Holly", "Ash", "Robin", "William" };
var ordered = names.ThenBy(x => x.Length);
那有什么意思?没有primary排序顺序(如果我使用的话就会有names.OrderBy(x => x)
),所以不可能强加中学排序。
我建议你try创建您自己的实现IOrderedEnumerable<T>
基于一个List<T>
- 当您尝试实施CreateOrderedEnumerable
方法,我想你会明白为什么它不合适。你可能会发现我的Edulinq 博客文章IOrderedEnumerable<T> http://codeblog.jonskeet.uk/2011/01/04/reimplementing-linq-to-objects-part-26a-iorderedenumerable/ useful.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)