Bu yapmalıyım
public static bool ContainsExactlyOneItem<T>(this IEnumerable<T> source)
{
using (IEnumerator<T> iterator = source.GetEnumerator())
{
return iterator.MoveNext() && !iterator.MoveNext();
}
}
Bu tür olduğunu funky olan hile, ama muhtemelen üretim kodunda kullanılmamalıdır. Sadece yeterince açık değil. Geldiğin ben sadece gördüm:)
DÜZENLEME; eğlenceli ederken & & operatörün LHS'deki yan etki RHS uygun çalışması için gerekli olması ... sadece kötü tam olarak aynı şey ile ama keyfi bir uzunluk için. Son dönüş ifadeniz yanlış olsa da - !en.MoveNext()
olmalıdır.
public static bool CountEquals<T>(this IEnumerable<T> source, int count)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count",
"count must not be negative");
}
// We don't rely on the optimizations in LINQ to Objects here, as
// they have changed between versions.
ICollection<T> genericCollection = source as ICollection<T>;
if (genericCollection != null)
{
return genericCollection.Count == count;
}
ICollection nonGenericCollection = source as ICollection;
if (nonGenericCollection != null)
{
return nonGenericCollection.Count == count;
}
// Okay, we're finally ready to do the actual work...
using (IEnumerator<T> iterator = source.GetEnumerator())
{
for (int i = 0; i < count; i++)
{
if (!iterator.MoveNext())
{
return false;
}
}
// Check we've got no more
return !iterator.MoveNext();
}
}
DÜZENLEME: Ve CountEquals
bir özyinelemeli formu (bu kullanmayın lütfen, fonksiyonel hayranları için şimdi İşte tam ICollection
/ICollection<T>
için güzel bir isim (IMO), argüman denetimi ve optimizasyonu ile yöntemidir bu) espri olsun diye sadece burada:
public static bool CountEquals<T>(this IEnumerable<T> source, int count)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count",
"count must not be negative");
}
using (IEnumerator<T> iterator = source.GetEnumerator())
{
return IteratorCountEquals(iterator, count);
}
}
private static bool IteratorCountEquals<T>(IEnumerator<T> iterator, int count)
{
return count == 0 ? !iterator.MoveNext()
: iterator.MoveNext() && IteratorCountEquals(iterator, count - 1);
}
DÜZENLEME: LINQ to SQL gibi bir şey için olduğunu unutmayın, basit Count()
yaklaşım kullanmalıdır - o veritabanına yerine getirilirken sonra yapılması gereken izin vereceğiz çünkü fiili sonuç. Listenin sıfır veya bir öğeye sahip olup olmadığını
Kodumda yaptığım mantık hatası, en azından * ve * tam olarak * ile ilgili olarak insanları atmış olabilir. Bence şu an en iyi çözüme ulaştık. – guhou
Sayımı(), geçirilen IEnumerable'un ICollection 'a verilmediğini belirlerse, yalnızca listenin tamamını yineler. Yani bir List örneğini veya bir diziyi iletirseniz, yinelenmez. –
Bence bu tamamen erken bir optimizasyon. –