Split a list into multiple lists at increasing sequence broken

前端 未结 9 1119
不知归路
不知归路 2021-02-18 19:11

I\'ve a List of int and I want to create multiple List after splitting the original list when a lower or same number is found. Numbers are not in sorted order.<

9条回答
  •  南笙
    南笙 (楼主)
    2021-02-18 19:58

    I really like Matthew Watson's solution. If however you do not want to rely on List, here is my simple generic approach enumerating the enumerable once at most and still retaining the capability for lazy evaluation.

    public static IEnumerable> AscendingSubsets(this IEnumerable superset) where T :IComparable
    {     
        var supersetEnumerator = superset.GetEnumerator();
    
        if (!supersetEnumerator.MoveNext())
        {
            yield break;
        }    
    
        T oldItem = supersetEnumerator.Current;
        List subset = new List() { oldItem };
    
        while (supersetEnumerator.MoveNext())
        {
            T currentItem = supersetEnumerator.Current;
    
            if (currentItem.CompareTo(oldItem) > 0)
            {
                subset.Add(currentItem);
            }
            else
            {
                yield return subset;
                subset = new List() { currentItem };
            }
    
            oldItem = supersetEnumerator.Current;
        }
    
        yield return subset;
    }
    

    Edit: Simplified the solution further to only use one enumerator.

提交回复
热议问题