ExactlyOne extension methodMy own implementation of Linq SelectMany extension methodA genric extension method to filter Linq-EF queriesTernary extension methodLazy man's IEnumerable extension verification methodExtension method to do Linq LookupsHelper for DropDownLists with extension methodValidation Extension method performanceRectangle ClassWriting a generic casting extension-methodstring.To2DCharArray extension method implementation
Adding gears to my grandson's 12" bike
Would using carbon dioxide as fuel work to reduce the greenhouse effect?
Why does the salt in the oceans not sink to the bottom?
How am I supposed to put out fires?
How to work a regular job as a former celebrity
Are gangsters hired to attack people at a train station classified as a terrorist attack?
How can I deal with someone that wants to kill something that isn't supposed to be killed?
Company requiring me to let them review research from before I was hired
What is a plausible power source to indefinitely sustain a space station?
Does quantity of data extensions impact performance?
Why are Oscar, India, and X-Ray (O, I, and X) not used as taxiway identifiers?
Can you find Airpod Case using Find my iPhone?
Is it ethical to tell my teaching assistant that I like him?
Bounded Torsion, without Mazur’s Theorem
Why is DC so, so, so Democratic?
What's the 1 inch size square knob sticking out of wall?
Extrapolation v. Interpolation
Why did computer video outputs go from digital to analog, then back to digital?
Can I pay with HKD in Macau or Shenzhen?
Has Peter Parker ever eaten bugs?
ExactlyOne extension method
German phrase for 'suited and booted'
Were Moshe's sons Jewish?
If I have the Armor of Shadows Eldritch Invocation do I know the Mage Armor spell?
ExactlyOne extension method
My own implementation of Linq SelectMany extension methodA genric extension method to filter Linq-EF queriesTernary extension methodLazy man's IEnumerable extension verification methodExtension method to do Linq LookupsHelper for DropDownLists with extension methodValidation Extension method performanceRectangle ClassWriting a generic casting extension-methodstring.To2DCharArray extension method implementation
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
I often find in codebases something on the order of if (sprockets.Count() > 0)
which is easily replaced with LINQ's if (sprockets.Any())
. This keeps the entirety of sprockets
from having to be iterated over completely (to get the count) then comparing to zero. Further, the business logic often reads something like "if there are any sprockets, inform the user of the subtotal". I also often see similar logic for exactly one of something: if (sprockets.Count() == 1)
which doesn't have an easy, low-cost LINQ alternative. So I've created one here:
public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source)
if (source is null)
throw new ArgumentNullException(nameof(source));
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
return enumerator.MoveNext() && !enumerator.MoveNext();
Usage is if (sprockets.ExactlyOne())
Here are unit tests. There is one helper method called Infinite()
which is a never-ending enumerable, which will baffle sprockets.Count()
, but not sprockets.ExactlyOne()
:
[TestClass]
public sealed class ExactlyOneTests
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestNull()
int[] nullArray = null;
Assert.IsFalse(nullArray.ExactlyOne());
[TestMethod]
public void TestZero()
int[] zero = Array.Empty<int>();
Assert.IsFalse(zero.ExactlyOne());
[TestMethod]
public void TestOne()
int[] one = 1 ;
Assert.IsTrue(one.ExactlyOne());
[TestMethod]
public void TestTwo()
int[] two = 1, 2 ;
Assert.IsFalse(two.ExactlyOne());
[TestMethod]
public void TestInfinite()
IEnumerable<int> infinite = Infinite();
Assert.IsFalse(infinite.ExactlyOne());
private static IEnumerable<int> Infinite()
while (true)
yield return 0;
Looking for overall review - is the code readable, maintainable, performant. Do the tests cover the expected cases or are there more to consider?
c# unit-testing linq extension-methods
$endgroup$
add a comment |
$begingroup$
I often find in codebases something on the order of if (sprockets.Count() > 0)
which is easily replaced with LINQ's if (sprockets.Any())
. This keeps the entirety of sprockets
from having to be iterated over completely (to get the count) then comparing to zero. Further, the business logic often reads something like "if there are any sprockets, inform the user of the subtotal". I also often see similar logic for exactly one of something: if (sprockets.Count() == 1)
which doesn't have an easy, low-cost LINQ alternative. So I've created one here:
public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source)
if (source is null)
throw new ArgumentNullException(nameof(source));
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
return enumerator.MoveNext() && !enumerator.MoveNext();
Usage is if (sprockets.ExactlyOne())
Here are unit tests. There is one helper method called Infinite()
which is a never-ending enumerable, which will baffle sprockets.Count()
, but not sprockets.ExactlyOne()
:
[TestClass]
public sealed class ExactlyOneTests
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestNull()
int[] nullArray = null;
Assert.IsFalse(nullArray.ExactlyOne());
[TestMethod]
public void TestZero()
int[] zero = Array.Empty<int>();
Assert.IsFalse(zero.ExactlyOne());
[TestMethod]
public void TestOne()
int[] one = 1 ;
Assert.IsTrue(one.ExactlyOne());
[TestMethod]
public void TestTwo()
int[] two = 1, 2 ;
Assert.IsFalse(two.ExactlyOne());
[TestMethod]
public void TestInfinite()
IEnumerable<int> infinite = Infinite();
Assert.IsFalse(infinite.ExactlyOne());
private static IEnumerable<int> Infinite()
while (true)
yield return 0;
Looking for overall review - is the code readable, maintainable, performant. Do the tests cover the expected cases or are there more to consider?
c# unit-testing linq extension-methods
$endgroup$
add a comment |
$begingroup$
I often find in codebases something on the order of if (sprockets.Count() > 0)
which is easily replaced with LINQ's if (sprockets.Any())
. This keeps the entirety of sprockets
from having to be iterated over completely (to get the count) then comparing to zero. Further, the business logic often reads something like "if there are any sprockets, inform the user of the subtotal". I also often see similar logic for exactly one of something: if (sprockets.Count() == 1)
which doesn't have an easy, low-cost LINQ alternative. So I've created one here:
public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source)
if (source is null)
throw new ArgumentNullException(nameof(source));
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
return enumerator.MoveNext() && !enumerator.MoveNext();
Usage is if (sprockets.ExactlyOne())
Here are unit tests. There is one helper method called Infinite()
which is a never-ending enumerable, which will baffle sprockets.Count()
, but not sprockets.ExactlyOne()
:
[TestClass]
public sealed class ExactlyOneTests
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestNull()
int[] nullArray = null;
Assert.IsFalse(nullArray.ExactlyOne());
[TestMethod]
public void TestZero()
int[] zero = Array.Empty<int>();
Assert.IsFalse(zero.ExactlyOne());
[TestMethod]
public void TestOne()
int[] one = 1 ;
Assert.IsTrue(one.ExactlyOne());
[TestMethod]
public void TestTwo()
int[] two = 1, 2 ;
Assert.IsFalse(two.ExactlyOne());
[TestMethod]
public void TestInfinite()
IEnumerable<int> infinite = Infinite();
Assert.IsFalse(infinite.ExactlyOne());
private static IEnumerable<int> Infinite()
while (true)
yield return 0;
Looking for overall review - is the code readable, maintainable, performant. Do the tests cover the expected cases or are there more to consider?
c# unit-testing linq extension-methods
$endgroup$
I often find in codebases something on the order of if (sprockets.Count() > 0)
which is easily replaced with LINQ's if (sprockets.Any())
. This keeps the entirety of sprockets
from having to be iterated over completely (to get the count) then comparing to zero. Further, the business logic often reads something like "if there are any sprockets, inform the user of the subtotal". I also often see similar logic for exactly one of something: if (sprockets.Count() == 1)
which doesn't have an easy, low-cost LINQ alternative. So I've created one here:
public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source)
if (source is null)
throw new ArgumentNullException(nameof(source));
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
return enumerator.MoveNext() && !enumerator.MoveNext();
Usage is if (sprockets.ExactlyOne())
Here are unit tests. There is one helper method called Infinite()
which is a never-ending enumerable, which will baffle sprockets.Count()
, but not sprockets.ExactlyOne()
:
[TestClass]
public sealed class ExactlyOneTests
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestNull()
int[] nullArray = null;
Assert.IsFalse(nullArray.ExactlyOne());
[TestMethod]
public void TestZero()
int[] zero = Array.Empty<int>();
Assert.IsFalse(zero.ExactlyOne());
[TestMethod]
public void TestOne()
int[] one = 1 ;
Assert.IsTrue(one.ExactlyOne());
[TestMethod]
public void TestTwo()
int[] two = 1, 2 ;
Assert.IsFalse(two.ExactlyOne());
[TestMethod]
public void TestInfinite()
IEnumerable<int> infinite = Infinite();
Assert.IsFalse(infinite.ExactlyOne());
private static IEnumerable<int> Infinite()
while (true)
yield return 0;
Looking for overall review - is the code readable, maintainable, performant. Do the tests cover the expected cases or are there more to consider?
c# unit-testing linq extension-methods
c# unit-testing linq extension-methods
edited 8 hours ago
Jesse C. Slicer
asked 9 hours ago
Jesse C. SlicerJesse C. Slicer
11.7k28 silver badges42 bronze badges
11.7k28 silver badges42 bronze badges
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
Q&A
Is the code readable?
ExactlyOne
states very clearly what the method is supposed to do.source is null
seems odd to me (does that even compile?). I'd prefersource == null
. (Edit from comments: a topic about is null vs == null)IEnumerator<TSource> enumerator = source.GetEnumerator()
can be written asvar enumerator = source.GetEnumerator()
.
Is the code maintainable?
- Since you are looking for a sibling function of
Any<T>()
, I would also include aExactlyOne<T>(Func<T, bool> predicate)
.
Is the code performant?
- It does seem so, right? But notice that LINQ is optimized for
IEnumerable<T>
that is alsoICollection<T>
, in which caseCount
is used. Implementations should have an eager implementation of this property. Your method should also use this optimizationCount == 1
. - I actually noticed (in my eyes) unexpected behavior in LINQ:
Count<T>()
is optimized forICollection<T>
butAny<T()
is not. This means you probably could make a slightly faster implementation than LINQ.
Do the tests cover the expected cases or are there more to consider?
You cover null
, empty, 1, multiple, early exit on infinite.. but perhaps also test on ICollection<T>
and custom IEnumerable<T>
implementations with eager and/or lazy loading.
Reference Source: LINQ Any vs Count
// not optimized for ICollection<T> (why ??)
public static bool Any<TSource>(this IEnumerable<TSource> source)
if (source == null) throw Error.ArgumentNull("source");
using (IEnumerator<TSource> e = source.GetEnumerator())
if (e.MoveNext()) return true;
return false;
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
if (source == null) throw Error.ArgumentNull("source");
if (predicate == null) throw Error.ArgumentNull("predicate");
foreach (TSource element in source)
if (predicate(element)) return true;
return false;
// optimized for ICollection<T>
public static int Count<TSource>(this IEnumerable<TSource> source)
if (source == null) throw Error.ArgumentNull("source");
ICollection<TSource> collectionoft = source as ICollection<TSource>;
if (collectionoft != null) return collectionoft.Count;
ICollection collection = source as ICollection;
if (collection != null) return collection.Count;
int count = 0;
using (IEnumerator<TSource> e = source.GetEnumerator())
checked
while (e.MoveNext()) count++;
return count;
$endgroup$
$begingroup$
Just one Q I'd like to address quickly while I'm thinking about it: I did try my hand at implementingExactlyOne<T>(Func<T, bool> predicate)
from first principles - it has to loop over the entire enumerable to run the predicate, so it would be functionally identical toCount<T>(Func<T, bool> predicate) == 1
. I suppose it would be orthogonal to implement it as that.
$endgroup$
– Jesse C. Slicer
8 hours ago
1
$begingroup$
Good thinking, it might very well be a complete clone of that method. On the other hand, I think it can be optimized with early exit when count > 1
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
source is null
- I read about that as well assource is object
(sorta likesource != null
) on some twitter feed from a noted developer, but the gist of it can be found here: gullberg.tk/blog/is-null-versus-null-in-c
$endgroup$
– Jesse C. Slicer
8 hours ago
1
$begingroup$
so is null means ReferenceEquals(null, source) then? I did not know this one
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
And I just added your suggestedICollection
optimization using C#7 pattern matching:if (source is ICollection<TSource> collection) return collection.Count == 1;
before theusing
. Thanks!
$endgroup$
– Jesse C. Slicer
8 hours ago
|
show 1 more comment
$begingroup$
This is for dfhwze as per comment:
public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
if (source is null)
throw new ArgumentNullException(nameof(source));
if (predicate is null)
throw new ArgumentNullException(nameof(predicate));
bool gotOne = false;
foreach (TSource element in source)
if (!predicate(element))
continue;
if (gotOne)
return false;
gotOne = true;
return gotOne;
$endgroup$
1
$begingroup$
Seems as optimized as I can think of. Early exit is the best you can do.
$endgroup$
– dfhwze
8 hours ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f224752%2fexactlyone-extension-method%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
Q&A
Is the code readable?
ExactlyOne
states very clearly what the method is supposed to do.source is null
seems odd to me (does that even compile?). I'd prefersource == null
. (Edit from comments: a topic about is null vs == null)IEnumerator<TSource> enumerator = source.GetEnumerator()
can be written asvar enumerator = source.GetEnumerator()
.
Is the code maintainable?
- Since you are looking for a sibling function of
Any<T>()
, I would also include aExactlyOne<T>(Func<T, bool> predicate)
.
Is the code performant?
- It does seem so, right? But notice that LINQ is optimized for
IEnumerable<T>
that is alsoICollection<T>
, in which caseCount
is used. Implementations should have an eager implementation of this property. Your method should also use this optimizationCount == 1
. - I actually noticed (in my eyes) unexpected behavior in LINQ:
Count<T>()
is optimized forICollection<T>
butAny<T()
is not. This means you probably could make a slightly faster implementation than LINQ.
Do the tests cover the expected cases or are there more to consider?
You cover null
, empty, 1, multiple, early exit on infinite.. but perhaps also test on ICollection<T>
and custom IEnumerable<T>
implementations with eager and/or lazy loading.
Reference Source: LINQ Any vs Count
// not optimized for ICollection<T> (why ??)
public static bool Any<TSource>(this IEnumerable<TSource> source)
if (source == null) throw Error.ArgumentNull("source");
using (IEnumerator<TSource> e = source.GetEnumerator())
if (e.MoveNext()) return true;
return false;
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
if (source == null) throw Error.ArgumentNull("source");
if (predicate == null) throw Error.ArgumentNull("predicate");
foreach (TSource element in source)
if (predicate(element)) return true;
return false;
// optimized for ICollection<T>
public static int Count<TSource>(this IEnumerable<TSource> source)
if (source == null) throw Error.ArgumentNull("source");
ICollection<TSource> collectionoft = source as ICollection<TSource>;
if (collectionoft != null) return collectionoft.Count;
ICollection collection = source as ICollection;
if (collection != null) return collection.Count;
int count = 0;
using (IEnumerator<TSource> e = source.GetEnumerator())
checked
while (e.MoveNext()) count++;
return count;
$endgroup$
$begingroup$
Just one Q I'd like to address quickly while I'm thinking about it: I did try my hand at implementingExactlyOne<T>(Func<T, bool> predicate)
from first principles - it has to loop over the entire enumerable to run the predicate, so it would be functionally identical toCount<T>(Func<T, bool> predicate) == 1
. I suppose it would be orthogonal to implement it as that.
$endgroup$
– Jesse C. Slicer
8 hours ago
1
$begingroup$
Good thinking, it might very well be a complete clone of that method. On the other hand, I think it can be optimized with early exit when count > 1
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
source is null
- I read about that as well assource is object
(sorta likesource != null
) on some twitter feed from a noted developer, but the gist of it can be found here: gullberg.tk/blog/is-null-versus-null-in-c
$endgroup$
– Jesse C. Slicer
8 hours ago
1
$begingroup$
so is null means ReferenceEquals(null, source) then? I did not know this one
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
And I just added your suggestedICollection
optimization using C#7 pattern matching:if (source is ICollection<TSource> collection) return collection.Count == 1;
before theusing
. Thanks!
$endgroup$
– Jesse C. Slicer
8 hours ago
|
show 1 more comment
$begingroup$
Q&A
Is the code readable?
ExactlyOne
states very clearly what the method is supposed to do.source is null
seems odd to me (does that even compile?). I'd prefersource == null
. (Edit from comments: a topic about is null vs == null)IEnumerator<TSource> enumerator = source.GetEnumerator()
can be written asvar enumerator = source.GetEnumerator()
.
Is the code maintainable?
- Since you are looking for a sibling function of
Any<T>()
, I would also include aExactlyOne<T>(Func<T, bool> predicate)
.
Is the code performant?
- It does seem so, right? But notice that LINQ is optimized for
IEnumerable<T>
that is alsoICollection<T>
, in which caseCount
is used. Implementations should have an eager implementation of this property. Your method should also use this optimizationCount == 1
. - I actually noticed (in my eyes) unexpected behavior in LINQ:
Count<T>()
is optimized forICollection<T>
butAny<T()
is not. This means you probably could make a slightly faster implementation than LINQ.
Do the tests cover the expected cases or are there more to consider?
You cover null
, empty, 1, multiple, early exit on infinite.. but perhaps also test on ICollection<T>
and custom IEnumerable<T>
implementations with eager and/or lazy loading.
Reference Source: LINQ Any vs Count
// not optimized for ICollection<T> (why ??)
public static bool Any<TSource>(this IEnumerable<TSource> source)
if (source == null) throw Error.ArgumentNull("source");
using (IEnumerator<TSource> e = source.GetEnumerator())
if (e.MoveNext()) return true;
return false;
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
if (source == null) throw Error.ArgumentNull("source");
if (predicate == null) throw Error.ArgumentNull("predicate");
foreach (TSource element in source)
if (predicate(element)) return true;
return false;
// optimized for ICollection<T>
public static int Count<TSource>(this IEnumerable<TSource> source)
if (source == null) throw Error.ArgumentNull("source");
ICollection<TSource> collectionoft = source as ICollection<TSource>;
if (collectionoft != null) return collectionoft.Count;
ICollection collection = source as ICollection;
if (collection != null) return collection.Count;
int count = 0;
using (IEnumerator<TSource> e = source.GetEnumerator())
checked
while (e.MoveNext()) count++;
return count;
$endgroup$
$begingroup$
Just one Q I'd like to address quickly while I'm thinking about it: I did try my hand at implementingExactlyOne<T>(Func<T, bool> predicate)
from first principles - it has to loop over the entire enumerable to run the predicate, so it would be functionally identical toCount<T>(Func<T, bool> predicate) == 1
. I suppose it would be orthogonal to implement it as that.
$endgroup$
– Jesse C. Slicer
8 hours ago
1
$begingroup$
Good thinking, it might very well be a complete clone of that method. On the other hand, I think it can be optimized with early exit when count > 1
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
source is null
- I read about that as well assource is object
(sorta likesource != null
) on some twitter feed from a noted developer, but the gist of it can be found here: gullberg.tk/blog/is-null-versus-null-in-c
$endgroup$
– Jesse C. Slicer
8 hours ago
1
$begingroup$
so is null means ReferenceEquals(null, source) then? I did not know this one
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
And I just added your suggestedICollection
optimization using C#7 pattern matching:if (source is ICollection<TSource> collection) return collection.Count == 1;
before theusing
. Thanks!
$endgroup$
– Jesse C. Slicer
8 hours ago
|
show 1 more comment
$begingroup$
Q&A
Is the code readable?
ExactlyOne
states very clearly what the method is supposed to do.source is null
seems odd to me (does that even compile?). I'd prefersource == null
. (Edit from comments: a topic about is null vs == null)IEnumerator<TSource> enumerator = source.GetEnumerator()
can be written asvar enumerator = source.GetEnumerator()
.
Is the code maintainable?
- Since you are looking for a sibling function of
Any<T>()
, I would also include aExactlyOne<T>(Func<T, bool> predicate)
.
Is the code performant?
- It does seem so, right? But notice that LINQ is optimized for
IEnumerable<T>
that is alsoICollection<T>
, in which caseCount
is used. Implementations should have an eager implementation of this property. Your method should also use this optimizationCount == 1
. - I actually noticed (in my eyes) unexpected behavior in LINQ:
Count<T>()
is optimized forICollection<T>
butAny<T()
is not. This means you probably could make a slightly faster implementation than LINQ.
Do the tests cover the expected cases or are there more to consider?
You cover null
, empty, 1, multiple, early exit on infinite.. but perhaps also test on ICollection<T>
and custom IEnumerable<T>
implementations with eager and/or lazy loading.
Reference Source: LINQ Any vs Count
// not optimized for ICollection<T> (why ??)
public static bool Any<TSource>(this IEnumerable<TSource> source)
if (source == null) throw Error.ArgumentNull("source");
using (IEnumerator<TSource> e = source.GetEnumerator())
if (e.MoveNext()) return true;
return false;
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
if (source == null) throw Error.ArgumentNull("source");
if (predicate == null) throw Error.ArgumentNull("predicate");
foreach (TSource element in source)
if (predicate(element)) return true;
return false;
// optimized for ICollection<T>
public static int Count<TSource>(this IEnumerable<TSource> source)
if (source == null) throw Error.ArgumentNull("source");
ICollection<TSource> collectionoft = source as ICollection<TSource>;
if (collectionoft != null) return collectionoft.Count;
ICollection collection = source as ICollection;
if (collection != null) return collection.Count;
int count = 0;
using (IEnumerator<TSource> e = source.GetEnumerator())
checked
while (e.MoveNext()) count++;
return count;
$endgroup$
Q&A
Is the code readable?
ExactlyOne
states very clearly what the method is supposed to do.source is null
seems odd to me (does that even compile?). I'd prefersource == null
. (Edit from comments: a topic about is null vs == null)IEnumerator<TSource> enumerator = source.GetEnumerator()
can be written asvar enumerator = source.GetEnumerator()
.
Is the code maintainable?
- Since you are looking for a sibling function of
Any<T>()
, I would also include aExactlyOne<T>(Func<T, bool> predicate)
.
Is the code performant?
- It does seem so, right? But notice that LINQ is optimized for
IEnumerable<T>
that is alsoICollection<T>
, in which caseCount
is used. Implementations should have an eager implementation of this property. Your method should also use this optimizationCount == 1
. - I actually noticed (in my eyes) unexpected behavior in LINQ:
Count<T>()
is optimized forICollection<T>
butAny<T()
is not. This means you probably could make a slightly faster implementation than LINQ.
Do the tests cover the expected cases or are there more to consider?
You cover null
, empty, 1, multiple, early exit on infinite.. but perhaps also test on ICollection<T>
and custom IEnumerable<T>
implementations with eager and/or lazy loading.
Reference Source: LINQ Any vs Count
// not optimized for ICollection<T> (why ??)
public static bool Any<TSource>(this IEnumerable<TSource> source)
if (source == null) throw Error.ArgumentNull("source");
using (IEnumerator<TSource> e = source.GetEnumerator())
if (e.MoveNext()) return true;
return false;
public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
if (source == null) throw Error.ArgumentNull("source");
if (predicate == null) throw Error.ArgumentNull("predicate");
foreach (TSource element in source)
if (predicate(element)) return true;
return false;
// optimized for ICollection<T>
public static int Count<TSource>(this IEnumerable<TSource> source)
if (source == null) throw Error.ArgumentNull("source");
ICollection<TSource> collectionoft = source as ICollection<TSource>;
if (collectionoft != null) return collectionoft.Count;
ICollection collection = source as ICollection;
if (collection != null) return collection.Count;
int count = 0;
using (IEnumerator<TSource> e = source.GetEnumerator())
checked
while (e.MoveNext()) count++;
return count;
edited 2 mins ago
answered 8 hours ago
dfhwzedfhwze
5,7501 gold badge8 silver badges36 bronze badges
5,7501 gold badge8 silver badges36 bronze badges
$begingroup$
Just one Q I'd like to address quickly while I'm thinking about it: I did try my hand at implementingExactlyOne<T>(Func<T, bool> predicate)
from first principles - it has to loop over the entire enumerable to run the predicate, so it would be functionally identical toCount<T>(Func<T, bool> predicate) == 1
. I suppose it would be orthogonal to implement it as that.
$endgroup$
– Jesse C. Slicer
8 hours ago
1
$begingroup$
Good thinking, it might very well be a complete clone of that method. On the other hand, I think it can be optimized with early exit when count > 1
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
source is null
- I read about that as well assource is object
(sorta likesource != null
) on some twitter feed from a noted developer, but the gist of it can be found here: gullberg.tk/blog/is-null-versus-null-in-c
$endgroup$
– Jesse C. Slicer
8 hours ago
1
$begingroup$
so is null means ReferenceEquals(null, source) then? I did not know this one
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
And I just added your suggestedICollection
optimization using C#7 pattern matching:if (source is ICollection<TSource> collection) return collection.Count == 1;
before theusing
. Thanks!
$endgroup$
– Jesse C. Slicer
8 hours ago
|
show 1 more comment
$begingroup$
Just one Q I'd like to address quickly while I'm thinking about it: I did try my hand at implementingExactlyOne<T>(Func<T, bool> predicate)
from first principles - it has to loop over the entire enumerable to run the predicate, so it would be functionally identical toCount<T>(Func<T, bool> predicate) == 1
. I suppose it would be orthogonal to implement it as that.
$endgroup$
– Jesse C. Slicer
8 hours ago
1
$begingroup$
Good thinking, it might very well be a complete clone of that method. On the other hand, I think it can be optimized with early exit when count > 1
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
source is null
- I read about that as well assource is object
(sorta likesource != null
) on some twitter feed from a noted developer, but the gist of it can be found here: gullberg.tk/blog/is-null-versus-null-in-c
$endgroup$
– Jesse C. Slicer
8 hours ago
1
$begingroup$
so is null means ReferenceEquals(null, source) then? I did not know this one
$endgroup$
– dfhwze
8 hours ago
1
$begingroup$
And I just added your suggestedICollection
optimization using C#7 pattern matching:if (source is ICollection<TSource> collection) return collection.Count == 1;
before theusing
. Thanks!
$endgroup$
– Jesse C. Slicer
8 hours ago
$begingroup$
Just one Q I'd like to address quickly while I'm thinking about it: I did try my hand at implementing
ExactlyOne<T>(Func<T, bool> predicate)
from first principles - it has to loop over the entire enumerable to run the predicate, so it would be functionally identical to Count<T>(Func<T, bool> predicate) == 1
. I suppose it would be orthogonal to implement it as that.$endgroup$
– Jesse C. Slicer
8 hours ago
$begingroup$
Just one Q I'd like to address quickly while I'm thinking about it: I did try my hand at implementing
ExactlyOne<T>(Func<T, bool> predicate)
from first principles - it has to loop over the entire enumerable to run the predicate, so it would be functionally identical to Count<T>(Func<T, bool> predicate) == 1
. I suppose it would be orthogonal to implement it as that.$endgroup$
– Jesse C. Slicer
8 hours ago
1
1
$begingroup$
Good thinking, it might very well be a complete clone of that method. On the other hand, I think it can be optimized with early exit when count > 1
$endgroup$
– dfhwze
8 hours ago
$begingroup$
Good thinking, it might very well be a complete clone of that method. On the other hand, I think it can be optimized with early exit when count > 1
$endgroup$
– dfhwze
8 hours ago
1
1
$begingroup$
source is null
- I read about that as well as source is object
(sorta like source != null
) on some twitter feed from a noted developer, but the gist of it can be found here: gullberg.tk/blog/is-null-versus-null-in-c$endgroup$
– Jesse C. Slicer
8 hours ago
$begingroup$
source is null
- I read about that as well as source is object
(sorta like source != null
) on some twitter feed from a noted developer, but the gist of it can be found here: gullberg.tk/blog/is-null-versus-null-in-c$endgroup$
– Jesse C. Slicer
8 hours ago
1
1
$begingroup$
so is null means ReferenceEquals(null, source) then? I did not know this one
$endgroup$
– dfhwze
8 hours ago
$begingroup$
so is null means ReferenceEquals(null, source) then? I did not know this one
$endgroup$
– dfhwze
8 hours ago
1
1
$begingroup$
And I just added your suggested
ICollection
optimization using C#7 pattern matching: if (source is ICollection<TSource> collection) return collection.Count == 1;
before the using
. Thanks!$endgroup$
– Jesse C. Slicer
8 hours ago
$begingroup$
And I just added your suggested
ICollection
optimization using C#7 pattern matching: if (source is ICollection<TSource> collection) return collection.Count == 1;
before the using
. Thanks!$endgroup$
– Jesse C. Slicer
8 hours ago
|
show 1 more comment
$begingroup$
This is for dfhwze as per comment:
public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
if (source is null)
throw new ArgumentNullException(nameof(source));
if (predicate is null)
throw new ArgumentNullException(nameof(predicate));
bool gotOne = false;
foreach (TSource element in source)
if (!predicate(element))
continue;
if (gotOne)
return false;
gotOne = true;
return gotOne;
$endgroup$
1
$begingroup$
Seems as optimized as I can think of. Early exit is the best you can do.
$endgroup$
– dfhwze
8 hours ago
add a comment |
$begingroup$
This is for dfhwze as per comment:
public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
if (source is null)
throw new ArgumentNullException(nameof(source));
if (predicate is null)
throw new ArgumentNullException(nameof(predicate));
bool gotOne = false;
foreach (TSource element in source)
if (!predicate(element))
continue;
if (gotOne)
return false;
gotOne = true;
return gotOne;
$endgroup$
1
$begingroup$
Seems as optimized as I can think of. Early exit is the best you can do.
$endgroup$
– dfhwze
8 hours ago
add a comment |
$begingroup$
This is for dfhwze as per comment:
public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
if (source is null)
throw new ArgumentNullException(nameof(source));
if (predicate is null)
throw new ArgumentNullException(nameof(predicate));
bool gotOne = false;
foreach (TSource element in source)
if (!predicate(element))
continue;
if (gotOne)
return false;
gotOne = true;
return gotOne;
$endgroup$
This is for dfhwze as per comment:
public static bool ExactlyOne<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
if (source is null)
throw new ArgumentNullException(nameof(source));
if (predicate is null)
throw new ArgumentNullException(nameof(predicate));
bool gotOne = false;
foreach (TSource element in source)
if (!predicate(element))
continue;
if (gotOne)
return false;
gotOne = true;
return gotOne;
answered 8 hours ago
Jesse C. SlicerJesse C. Slicer
11.7k28 silver badges42 bronze badges
11.7k28 silver badges42 bronze badges
1
$begingroup$
Seems as optimized as I can think of. Early exit is the best you can do.
$endgroup$
– dfhwze
8 hours ago
add a comment |
1
$begingroup$
Seems as optimized as I can think of. Early exit is the best you can do.
$endgroup$
– dfhwze
8 hours ago
1
1
$begingroup$
Seems as optimized as I can think of. Early exit is the best you can do.
$endgroup$
– dfhwze
8 hours ago
$begingroup$
Seems as optimized as I can think of. Early exit is the best you can do.
$endgroup$
– dfhwze
8 hours ago
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f224752%2fexactlyone-extension-method%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown