如何在C#中爲空集合使用默認值IEnumerable.Max?C#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> { });
}
不要編輯答案到你的問題,接受的答案... – Magus
抱歉。一旦計時器允許我這樣做,我會接受。 – user2684301
請恢復更改! – rae1