c# – 使用Linq将数据分区为数组

前端之家收集整理的这篇文章主要介绍了c# – 使用Linq将数据分区为数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个元素数组,其中元素具有Flagged布尔值.
1 flagged
2 not flagged
3 not flagged
4 flagged
5 not flagged
6 not flagged
7 not flagged
8 flagged
9 not flagged

我想根据标记的指标将其分解为数组

输出>

array 1 {1,2,3}
array 2 {4,5,6,7}
array 3 {8,9}

解决方法

Linq没有这方面的操作符,但我编写了一个你可以使用的扩展方法(在提交到 MoreLinq的过程中,你也应该检查):

使用下面的运算符,你会写:

var result = 
   items.Segment( (item,prevItem,idx) => item.Flagged )
        .Select( seq => seq.ToArray() )  // converts each sequence to an array
        .ToList();

这是扩展方法代码

public static IEnumerable<IEnumerable<T>> Segment<T>(IEnumerable<T> sequence,Func<T,T,int,bool> newSegmentIdentifier) 
     { 
         var index = -1; 
         using (var iter = sequence.GetEnumerator()) 
         { 
             var segment = new List<T>(); 
             var prevItem = default(T); 

             // ensure that the first item is always part 
             // of the first segment. This is an intentional 
             // behavior. Segmentation always begins with 
             // the second element in the sequence. 
             if (iter.MoveNext()) 
             { 
                 ++index; 
                 segment.Add(iter.Current); 
                 prevItem = iter.Current; 
             } 

             while (iter.MoveNext()) 
             { 
                 ++index; 
                 // check if the item represents the start of a new segment 
                 var isNewSegment = newSegmentIdentifier(iter.Current,index); 
                 prevItem = iter.Current; 

                 if (!isNewSegment) 
                 { 
                     // if not a new segment,append and continue 
                     segment.Add(iter.Current); 
                     continue; 
                 } 
                 yield return segment; // yield the completed segment 

                 // start a new segment... 
                 segment = new List<T> { iter.Current }; 
             } 
             // handle the case of the sequence ending before new segment is detected 
             if (segment.Count > 0) 
                 yield return segment; 
         } 
     }
原文链接:/csharp/97436.html

猜你在找的C#相关文章