int constrainedCount = yourSequence.Take(2).Count();
// if constrainedCount == 0 then the sequence is empty
// if constrainedCount == 1 then the sequence contains a single element
// if constrainedCount == 2 then the sequence has more than one element
1 つの方法は、新しい拡張メソッドを作成することです
public static bool IsSingle<T>(this IEnumerable<T> enumerable) {
using (var enumerator = enumerable.GetEnumerator()) {
if (!enumerator.MoveNext()) {
return false;
}
return !enumerator.MoveNext();
}
}
このコードは、LukeH の優れた回答を採用し、IEnumerable
としてまとめています。 コードが None
の観点から処理できるように拡張します 、 One
そして Many
0
ではなく 、 1
そして 2
.
public enum Multiplicity
{
None,
One,
Many,
}
静的クラスでは、例えばEnumerableExtensions
:
public static Multiplicity Multiplicity<TElement>(this IEnumerable<TElement> @this)
{
switch (@this.Take(2).Count())
{
case 0: return General.Multiplicity.None;
case 1: return General.Multiplicity.One;
case 2: return General.Multiplicity.Many;
default: throw new Exception("WTF‽");
}
}