Giả sử tôi muốn kiểm tra xem có ít nhất N phần tử trong bộ sưu tập hay không.LINQ Count() cho đến khi, điều này có hiệu quả hơn không?
Điều này có tốt hơn là làm không?
Count() >= N
Sử dụng:
public static bool AtLeast<T>(this IEnumerable<T> enumerable, int max)
{
int count = 0;
return enumerable.Any(item => ++count >= max);
}
Hoặc thậm chí
public static bool Equals<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount).Count() == amount;
}
Làm thế nào có thể tôi chuẩn này?
/// <summary>
/// Returns whether the enumerable has at least the provided amount of elements.
/// </summary>
public static bool HasAtLeast<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount).Count() == amount;
}
/// <summary>
/// Returns whether the enumerable has at most the provided amount of elements.
/// </summary>
public static bool HasAtMost<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount + 1).Count() <= amount;
}
_How thể tôi chuẩn này _ - Đặt mã bạn thường sử dụng để gọi chúng trong một vòng lặp với thời gian ..? –
một tùy chọn khác: enumerable.Select ((o, idx) => idx). Bất kỳ (i => i> = max); – KristoferA