一、字符串類型最大值
1.字符串類型的最大值,和數據庫的字典排序最后一個相同,如果存在返回null
- //字符串最大值,是字典排序最后一個
- string max1 = _context.students.Max(q => q.sname);
- Console.WriteLine(max1);
- //字符串最大值,如果不存在返回null
- string max2 = _context.students
- .Where(q => false)
- .Max(q => q.sname);
- Console.WriteLine(max2);
- Console.WriteLine(max2 == null); //True
- Console.WriteLine(max2 == ""); //False
//字符串最大值,是字典排序最后一個 string max1 = _context.students.Max(q => q.sname); Console.WriteLine(max1); //字符串最大值,如果不存在返回null string max2 = _context.students .Where(q => false) .Max(q => q.sname); Console.WriteLine(max2); Console.WriteLine(max2 == null); //True Console.WriteLine(max2 == ""); //False
二、數字類型最大值
1.數字類型最大值,和數據庫字段排序最后一個相同,如果沒有數據拋出異常。
- //數字類型,獲取最大值為正序排列最后一個值
- decimal deci1 = _context.scores.Max(q => q.degree);
- Console.WriteLine(deci1);
//數字類型,獲取最大值為正序排列最后一個值 decimal deci1 = _context.scores.Max(q => q.degree); Console.WriteLine(deci1);
數字類型,獲取條件的數據不存在拋出異常
其他信息: 到值類型“System.Decimal”的強制轉換失敗,因為具體化值為 null。
結果類型的泛型參數或查詢必須使用可以為 null 的類型。
- decimal deci2 = _context.scores.Where(q => false).Max(q => q.degree);
- Console.WriteLine(deci2);
decimal deci2 = _context.scores.Where(q => false).Max(q => q.degree); Console.WriteLine(deci2);
解決方案1:
- //解決方案1,使用DefaultIfEmpty(),推薦
- var query = _context.scores.Where(q => false)
- .Select(q => q.degree)
- .DefaultIfEmpty();
- Console.WriteLine(query.ToString());
- decimal deci3 = query
- .Max();
- Console.WriteLine(deci3);
//解決方案1,使用DefaultIfEmpty(),推薦 var query = _context.scores.Where(q => false) .Select(q => q.degree) .DefaultIfEmpty(); Console.WriteLine(query.ToString()); decimal deci3 = query .Max(); Console.WriteLine(deci3);
生成sql如下:
解決方案2:
- //解決方案2,先判斷再取值,執行兩次數據庫查詢
- decimal deci4 = 0;
- if (_context.scores.Any())
- {
- deci4 = _context.scores.Max(q => q.degree);
- }
- Console.WriteLine(deci4);
//解決方案2,先判斷再取值,執行兩次數據庫查詢 decimal deci4 = 0; if (_context.scores.Any()) { deci4 = _context.scores.Max(q => q.degree); } Console.WriteLine(deci4);
解決方案3:
- //解決方案3,內存取最大值
- decimal deci5 = _context.scores
- .Select(q => q.degree)
- .ToList()
- .Max();
- Console.WriteLine(deci5);
//解決方案3,內存取最大值 decimal deci5 = _context.scores .Select(q => q.degree) .ToList() .Max(); Console.WriteLine(deci5);