不要LINQ的可枚举的方法维护元素的相对顺序? [英] Do LINQ's Enumerable Methods Maintain Relative Order of Elements?

查看:304
本文介绍了不要LINQ的可枚举的方法维护元素的相对顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有列表<富> FOOS ,其中当前的元素顺序很重要。如果我再申请一个LINQ可枚举的方法,如 GROUPBY 其中,选择,我可以依靠所产生的的IEnumerable<富> 在相同的相对顺序与原来的名单进行迭代

Say I have List<Foo> foos where the current order of elements is important. If I then apply a LINQ Enumerable method such as GroupBy, Where or Select, can I rely on the resulting IEnumerable<Foo> to iterate in the same relative order as the original list?

推荐答案

是的,可枚举方法(LINQ到对象,它适用于列表< T> ; 你所提到的),你可以依赖由选择返回元素的顺序其中, GROUPBY 。这不是事情的本质无序像 ToDictionary 鲜明

Yes, for Enumerable methods (LINQ to Objects, which applies to List<T> you mentioned), you can rely on the order of elements returned by Select, Where, or GroupBy. This is not the case for things that are inherently unordered like ToDictionary or Distinct.

IGrouping< TKEY的,TElement> 对象产生的顺序基于源元素的顺序所产生的每个 IGrouping<的第一个关键; TKEY的,TElement> 。在分组的元素产生在他们出现在的顺序。

From Enumerable.GroupBy documentation:

The IGrouping<TKey, TElement> objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping<TKey, TElement>. Elements in a grouping are yielded in the order they appear in source.

这不是的IQueryable 一定是真实的扩展方法(其他LINQ提供程序)。

This is not necessarily true for IQueryable extension methods (other LINQ providers).

这篇关于不要LINQ的可枚举的方法维护元素的相对顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆