2014-02-18 50 views
-2

我有這樣的代碼:奇怪LINQ行爲

在這裏我從數據庫中獲取多頭的列表:

IQueryable<long> query = from t in table select t.LongId 

在這裏,我嘗試從這些ID獲得最大的:

long max = query.Any() ? query.Max() : 0; 

但無論查詢的結果是多少,max始終設置爲0.

你有什麼想法w HY?

+0

如何調試呢? query.Any()返回什麼,query.Max()返回什麼? – nvoigt

+0

1)這兩行之間是否有其他代碼? 2)什麼是「表」和它有什麼數據? –

+0

你確定查詢不是空的嗎? –

回答

4

如果

long max = query.Any() ? query.Max() : 0; 

回報爲零,則以下條件之一爲真:

  1. 查詢不返回任何結果
  2. 查詢結果中的最大值爲零

當您在定義查詢和從查詢中獲取最大值之間修改表時,可能會出現第一種情況。請記住 - query沒有任何數據。它只是查詢定義,只有在執行查詢時(例如調用Any()或Max())纔會獲取數據。

測試:

List<long> table = new List<long> { 1, 2, 3 }; 
var query = from t in table select t; // query is not executed 
table.Clear(); // modify data source before query is executed 
Assert.False(query.Any()); // execute query on modified data source 
2

難道這不是更簡單嗎?

long max = table.OrderByDescending(t => t.LongId) 
       .Select(t => t.LongId) 
       .FirstOrDefault() ?? 0; 
1

最簡單的方法:

var maxId = table.OrderByDescending(x => x.LongId).First().LongId;