Native C# support for checking if an IEnumerable is sorted?

前端 未结 5 1798
不知归路
不知归路 2020-12-19 13:00

Is there any LINQ support for checking if an IEnumerable is sorted? I have an enumerable that I want to verify is sorted in non-descending order, but I

5条回答
  •  旧巷少年郎
    2020-12-19 13:31

    There is a short and simple version using Zip, although your IEnumerable does get enumerated twice.

    var source = Enumerable.Range(1,100000);

    bool isSorted = source.Zip(source.Skip(1),(a,b)=>b>=a).All(x=>x);

提交回复
热议问题