# [c#] 最大或默認？

``````int max = list.Max(i => (int?)i.MyCounter) ?? 0;
``````
Question

``````Dim x = (From y In context.MyTable _
Where y.MyField = value _
Select y.MyCounter).Max
``````

``````Dim x = (From y In context.MyTable _
Where y.MyField = value _
Select y.MyCounter _
Order By MyCounter Descending).FirstOrDefault
``````

``````int max = list.Any() ? list.Max(i => i.MyCounter) : 0;
``````

``````Try
Dim x = (From y In context.MyTable _
Where y.MyField = value _
Select y.MyCounter).Max
... continue working with x ...
Catch ex As SqlException
... do error processing ...
End Try
``````

{1,2,3，-1，-2，-3}的最大值顯然是3. {2}的最大值明顯是2.但是空集{}的最大值是多少？ 顯然這是一個毫無意義的問題。 空集的最大值沒有被定義。 試圖獲得答案是一個數學錯誤。 任何集合的最大值本身都必須是該集合中的一個元素。 空集沒有元素，所以聲稱某個特定的數字是該集中的最大值而不在該集合中是數學矛盾。

``````    public static TResult MaxOrDefault<TSource, TResult>(this
IQueryable<TSource> source, Expression<Func<TSource, TResult?>> selector,
TResult defaultValue = default (TResult)) where TResult : struct
{
return source.Max(selector) ?? defaultValue;
}
``````

``````    sequence.DefaultOrMax(s => (int?)s.Id);
``````

``````(From y In context.MyTable _
Where y.MyField = value _
Select y.MyCounter)
``````

``````var max = new[]{0}
.Concat((From y In context.MyTable _
Where y.MyField = value _
Select y.MyCounter))
.Max();
``````

``````var max = new[]{0}
.Concat((From y In context.MyTable _
Where y.MyField = value _
Select y.MyCounter))
.Max();
``````

System.NotSupportedException：LINQ to Entities不支持LINQ表達式節點類型'NewArrayInit'。

``````(From y In context.MyTable _
Where y.MyField = value _
Select y.MyCounter))
.OrderByDescending(x=>x).FirstOrDefault());
``````

``````decimal Max = (decimal?)(context.MyTable.Select(e => e.MyCounter).Max()) ?? 0;
``````