如果返回类型为 IEnumerable,是否可以保证订单?

发布于 2025-01-11 10:26:19 字数 620 浏览 1 评论 0原文

我目前正在重构一些代码,并遇到了这种方法。

    public IEnumerable<KeyValuePair<string, string>> GetDataItems()

    var data = EditorService
        .GetAllItem()
       .OrderBy(x => x.name);

    var list = new List<KeyValuePair<string, string>>();

    foreach (var item in data)
    {
        string guid = item.guid;
        string name = item.name;
        list.Add(new KeyValuePair<string, string>(guid, name));
    }

    return list;

我对订单本身是否有意义感到有点困惑 据我了解,IEnumerable 不能确保列表中的对象没有排序? 但在这种情况下,底层模型是一个列表,那么顺序能得到保证吗? 或者返回后会被忽略吗?

I am currently working on refactoring some code, and came across this method.

    public IEnumerable<KeyValuePair<string, string>> GetDataItems()

which does this

    var data = EditorService
        .GetAllItem()
       .OrderBy(x => x.name);

    var list = new List<KeyValuePair<string, string>>();

    foreach (var item in data)
    {
        string guid = item.guid;
        string name = item.name;
        list.Add(new KeyValuePair<string, string>(guid, name));
    }

    return list;

I am bit confused on whether the order itself make sense?
IEnumerable as I understand don't ensure that objects in the list is not ordered?
But in this case the underlying model is a list, will order then be guranteed?
or will this be ignored once it is returned?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

单挑你×的.吻 2025-01-18 10:26:19

您在代码片段中显示的变量数据属于该 OrderBy linq 语句返回的 System.Linq.IOrderedEnumerable 类型。
因此,您在返回的列表中插入的项目是有序的。正如您所说,您添加到该列表中的新项目不能保证其订单。

The variable data you show on your code snippet is of type System.Linq.IOrderedEnumerable returned by that OrderBy linq statement.
The items you inserted on your returned list are ordered because of that. New items you add on that list, as you told, are not guranteed their order.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文