Preserving order with LINQ(使用 LINQ 保持顺序)
问题描述
I use LINQ to Objects instructions on an ordered array. Which operations shouldn't I do to be sure the order of the array is not changed?
I examined the methods of System.Linq.Enumerable, discarding any that returned non-IEnumerable results. I checked the remarks of each to determine how the order of the result would differ from order of the source.
Preserves Order Absolutely. You can map a source element by index to a result element
- AsEnumerable
 - Cast
 - Concat
 - Select
 - ToArray
 - ToList
 
Preserves Order. Elements are filtered or added, but not re-ordered.
- Distinct
 - Except
 - Intersect
 - OfType
 - Prepend (new in .net 4.7.1)
 - Skip
 - SkipWhile
 - Take
 - TakeWhile
 - Where
 - Zip (new in .net 4)
 
Destroys Order - we don't know what order to expect results in.
- ToDictionary
 - ToLookup
 
Redefines Order Explicitly - use these to change the order of the result
- OrderBy
 - OrderByDescending
 - Reverse
 - ThenBy
 - ThenByDescending
 
Redefines Order according to some rules.
- GroupBy - The IGrouping objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping. Elements in a grouping are yielded in the order they appear in source.
 - GroupJoin - GroupJoin preserves the order of the elements of outer, and for each element of outer, the order of the matching elements from inner.
 - Join - preserves the order of the elements of outer, and for each of these elements, the order of the matching elements of inner.
 - SelectMany - for each element of source, selector is invoked and a sequence of values is returned.
 - Union - When the object returned by this method is enumerated, Union enumerates first and second in that order and yields each element that has not already been yielded.
 
Edit: I've moved Distinct to Preserving order based on this implementation.
    private static IEnumerable<TSource> DistinctIterator<TSource>
      (IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
    {
        Set<TSource> set = new Set<TSource>(comparer);
        foreach (TSource element in source)
            if (set.Add(element)) yield return element;
    }
这篇关于使用 LINQ 保持顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 LINQ 保持顺序
				
        
 
            
        基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
 - 全局 ASAX - 获取服务器名称 2022-01-01
 - 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
 - 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
 - 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
 - 首先创建代码,多对多,关联表中的附加字段 2022-01-01
 - 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
 - 错误“此流不支持搜索操作"在 C# 中 2022-01-01
 - 如何动态获取文本框中datagridview列的总和 2022-01-01
 - 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				