How do I do IEnumerable.Max with a default value for empty collections in C#?
Here is what I want to do in Java 8:
public static void doTest(List<String> l) {
System.out.println("max string is: " + l.stream().max((a, b) -> a.compareToIgnoreCase(b)).orElse("default"));
System.out.println("max length is: " + l.stream().mapToInt(s -> s.length()).max().orElse(-1));
}
public static void main(String[] args) throws Exception {
System.out.println("Test with non-empty list");
doTest(Arrays.asList("alpha", "beta", "charlie", "gamma"));
System.out.println("");
System.out.println("Test with empty list");
doTest(Arrays.asList());
}
Here is what I have in C# so far:
static void DoTest(List<String> l) {
Console.WriteLine("max string is: " + l.Max());
Console.WriteLine("max length is: " + l.Select(s => s.Length).Max());
}
static void Main() {
Console.WriteLine("Test with non-empty list");
DoTest(new List<String> { "alpha", "beta", "charlie", "gamma" });
Console.WriteLine("");
Console.WriteLine("Test with empty list");
DoTest(new List<String> { });
}
I'd just use DefaultIfEmpty
:
int maxLength = l.Select(s => s.Length).DefaultIfEmpty().Max();
Or to specify a default:
int maxLength = l.Select(s => s.Length).DefaultIfEmpty(-1).Max();
Or use a nullable value so you can tell the different:
int? maxLength = l.Select(s => (int?) s.Length).Max();
Then maxLength
will be null
if l
is empty.
See more on this question at Stackoverflow