是否有任何 LINQ 支持检查 IEnumerable<T>
是否存在?排序了吗?我有一个要验证的可枚举项是否按非降序排序,但我似乎无法在 C# 中找到对它的原生支持。
我使用 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;
}
最佳答案
您可以检查集合是否为 IOrderedEnumerable
但这只有在排序是应用于序列的最后一个操作时才有效。所以,基本上你需要手动检查所有序列。
还要记住,如果序列是 IOrderedEnumerable
你真的不能说哪个条件用于排序序列。
这是一个通用方法,您可以使用它来检查序列是否按您要检查的字段按升序排序:
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
.
关于c# - native C# 支持检查 IEnumerable 是否已排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19786101/