gpt4 book ai didi

c# - 为什么 List 不实现 IOrderedEnumerable

转载 作者:可可西里 更新时间:2023-11-01 08:35:19 25 4
gpt4 key购买 nike

我想使用有序的枚举,并使用接口(interface)作为返回类型而不是具体类型。我需要返回一组有序的对象。但是,当使用 IList<T> 时执行我不能返回IOrderedEnumerable<T> , 作为 IList<T>不继承IOrderedEnumerable<T>

在下面的示例中,我有一个带有系列存储库的 View 模型,实现为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?

编辑:澄清我的意图:我只是想在接口(interface)级别声明,我的存储库有一个订单,即使它没有明确指定一个键。因此,.ThenBy等人不应添加新订单,因为已经有一个 - 我自己的一个,而且是唯一一个。 :-)。我明白了,像这样,我想念 .ThenBy 的意图.

最佳答案

怎么可能 List<T>实现 IOrderedEnumerable<T> ?它必须提供一种创建后续排序的方法……这到底是什么意思?

考虑一下:

var names = new List<string> { "Jon", "Holly", "Ash", "Robin", "William" };
var ordered = names.ThenBy(x => x.Length);

那到底是什么意思?没有主要排序顺序(如果我使用 names.OrderBy(x => x) 就会有),所以不可能强加次要排序顺序。

我建议您尝试创建自己的 IOrderedEnumerable<T> 实现基于 List<T> - 当您尝试实现 CreateOrderedEnumerable方法,我想你会明白为什么它不合适。你可以找到我的 Edulinq blog post on IOrderedEnumerable<T> 有用。

关于c# - 为什么 List<T> 不实现 IOrderedEnumerable<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5429974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com