Hi everyone,
Quick question, what's the preferable way to programmaticaly ask "Is there exactly one element in this sequence that satisfies X condition?" using Linq?
i.e.
// Pretend that the .OneAndOnlyOne() method exists
int[] sequence = new int[] { 1, 1, 2, 3, 5, 8 };
Assert.IsTrue(sequence.OneAndOnlyOne(x => x == 2);
Assert.IsFalse(sequence.OneAndOnlyOne(x => x == 1);
something like this can be done with:
sequence.SingleOrDefault(x => x == 2) != null;
but that's a little clunky.
I suppose I could roll my own extension method, but this seems to be a common pattern in my code and I want to make sure there's a good clean way to do it. Is there a way using the built-in LINQ methods?
Thanks!
-Mike