如何使用C#中的空集合的默认值执行IEnumerable.Max?
以下是我想在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());
}
到目前为止,这是我在C#中所拥有的:
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> { });
}
答案 0 :(得分:6)
我只是使用DefaultIfEmpty
:
int maxLength = l.Select(s => s.Length).DefaultIfEmpty().Max();
或指定默认值:
int maxLength = l.Select(s => s.Length).DefaultIfEmpty(-1).Max();
或使用可以为空的值,以便您可以分辨出不同的内容:
int? maxLength = l.Select(s => (int?) s.Length).Max();
如果maxLength
为空,则null
将为l
。