patterncsharpMinor
Add the first non-null item from one list to another list
Viewed 0 times
itemthenonnullonefirstanotherlistfromadd
Problem
Given these two methods, is it defensible that one is better than the other?
In what terms? Performance? Elegance? Readability?
In what terms? Performance? Elegance? Readability?
public static void AddFirstNotNull(List onlyNotNull, List source)
{
var item = source.FirstOrDefault(v => v != null);
if (item != null)
{
onlyNotNull.Add(item);
}
}
public static void AddFirstNotNull(List onlyNotNull, List source)
{
onlyNotNull.AddRange(source.Where(v => v != null).Take(1));
}Solution
I agree with @RickDavin that the first function expresses its intent in a more obvious way.
My main concern, though, is that neither function provides feedback as to whether the operation actually resulted in any change. The function should return a boolean. It's easy to modify the first function to return a boolean, but not the second.
My main concern, though, is that neither function provides feedback as to whether the operation actually resulted in any change. The function should return a boolean. It's easy to modify the first function to return a boolean, but not the second.
Context
StackExchange Code Review Q#121672, answer score: 4
Revisions (0)
No revisions yet.