本机C#支持检查IEnumerable是否已排序? [英] Native C# support for checking if an IEnumerable is sorted?
问题描述
是否有LINQ支持检查IEnumerable<T>
是否已排序?我有一个要验证的枚举以非降序排列,但似乎无法在C#中找到对此的原生支持.
Is there any LINQ support for checking if an IEnumerable<T>
is sorted? I have an enumerable that I want to verify is sorted in non-descending order, but I can't seem to find native support for it in C#.
我已经使用IComparables<T>
编写了自己的扩展方法:
I've written my own extension method using IComparables<T>
:
public static bool IsSorted<T>(this IEnumerable<T> collection) where T : IComparable<T>
{
Contract.Requires(collection != null);
using (var enumerator = collection.GetEnumerator())
{
if (enumerator.MoveNext())
{
var previous = enumerator.Current;
while (enumerator.MoveNext())
{
var current = enumerator.Current;
if (previous.CompareTo(current) > 0)
return false;
previous = current;
}
}
}
return true;
}
一个使用IComparer<T>
对象的对象:
public static bool IsSorted<T>(this IEnumerable<T> collection, IComparer<T> comparer)
{
Contract.Requires(collection != null);
using (var enumerator = collection.GetEnumerator())
{
if (enumerator.MoveNext())
{
var previous = enumerator.Current;
while (enumerator.MoveNext())
{
var current = enumerator.Current;
if (comparer.Compare(previous, current) > 0)
return false;
previous = current;
}
}
}
return true;
}
推荐答案
您可以检查collection是否为IOrderedEnumerable
,但这仅在排序是应用于序列的最后一个操作时才有效.因此,基本上,您需要手动检查所有序列.
You can check if collection is IOrderedEnumerable
but that will work only if ordering is the last operation which was applied to sequence. So, basically you need to check all sequence manually.
还请记住,如果序列是IOrderedEnumerable
,则您真的不能说是使用哪个条件对序列进行排序的.
Also keep in mind, that if sequence is IOrderedEnumerable
you really can't say which condition was used to sort sequence.
这是通用方法,可用于检查序列是否按要检查的字段按升序排序:
Here is generic method which you can use to check if sequence is sorted in ascending order by field you want to check:
public static bool IsOrdered<T, TKey>(
this IEnumerable<T> source, Func<T, TKey> keySelector)
{
if (source == null)
throw new ArgumentNullException("source");
var comparer = Comparer<TKey>.Default;
using (var iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
return true;
TKey current = keySelector(iterator.Current);
while (iterator.MoveNext())
{
TKey next = keySelector(iterator.Current);
if (comparer.Compare(current, next) > 0)
return false;
current = next;
}
}
return true;
}
用法:
string[] source = { "a", "ab", "c" };
bool isOrdered = source.IsOrdered(s => s.Length);
您可以创建类似的IsOrderedDescending
方法-只需将检查比较结果更改为comparer.Compare(current, next) < 0
.
You can create similar IsOrderedDescending
method - just change checking comparison result to comparer.Compare(current, next) < 0
.
这篇关于本机C#支持检查IEnumerable是否已排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!