Split a list into multiple lists at increasing sequence broken

前端 未结 9 1149
不知归路
不知归路 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 20:00

    This is my simple loop approach using some yields :

    static IEnumerable<IList<int>> Split(IList<int> data) { if (data.Count == 0) yield break; List<int> curr = new List<int>(); curr.Add(data[0]); int last = data[0]; for (int i = 1; i < data.Count; i++) { if (data[i] <= last) { yield return curr; curr = new List<int>(); } curr.Add(data[i]); last = data[i]; } yield return curr; }

    0 讨论(0)
  • 2021-02-18 20:01

    I have modified your code, and now working fine:

            List<int> data = new List<int> { 1, 2, 1, 2, 3,3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 6 };
            List<List<int>> resultLists = new List<List<int>>();
            int last = 0;
            int count = 0;
    
            var res = data.Where((p, i) =>
            {
                if (i > 0)
                {
                    if (p > last && p!=last)
                    {
                        resultLists[count].Add(p);
                    }
                    else
                    {
                        count++;
                        resultLists.Add(new List<int>());
                        resultLists[count].Add(p);
                    }
                }
                else
                {
                    resultLists.Add(new List<int>());
                    resultLists[count].Add(p);
                }
    
    
    
                last = p;
                return true;
            }).ToList();
    
    0 讨论(0)
  • 2021-02-18 20:05

    This is not a typical LINQ operation, so as usual in such cases (when one insists on using LINQ) I would suggest using Aggregate method:

    var result = data.Aggregate(new List<List<int>>(), (r, n) =>
    {
        if (r.Count == 0 || n <= r.Last().Last()) r.Add(new List<int>());
        r.Last().Add(n);
        return r;
    });
    
    0 讨论(0)
提交回复
热议问题