gpt4 book ai didi

c# - native C# 支持检查 IEnumerable 是否已排序?

转载 作者:太空狗 更新时间:2023-10-30 01:05:13 25 4
gpt4 key购买 nike

是否有任何 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com