2015-09-27 46 views
-2

這裏是我的linq代碼我想用linq過濾一個列表,但是在這種情況下它看起來不起作用,並且不返回一個帶有ItemName == stringItemName匹配的列表,Linq where does not work。Where

JsonResult jso = Json(ItemList 
       .Where(x => x.ItemName==stringItemName) 
       .Select(x => new { x.Year }).Distinct() 
       .Select(x => new { Text = x.Year.ToShortDateString(), Value = x.ToShortDateString() })); 

也不

JsonResult jso = Json(ItemList 
       .Where(x => x.ItemName.Equals(stringItemName)) 
       .Select(x => new { x.Year }).Distinct() 
       .Select(x => new { Text = x.Year.ToShortDateString(), Value = x.ToShortDateString() })); 

我不知道爲什麼它在過去的工作中不同的場景,但現在難道不工作。我在做什麼錯...

+0

是你比較的字符串屬性? –

+4

你是什麼意思,它不起作用?你是否收到錯誤信息,或者沒有編譯或做它,只是沒有給出預期的結果? – grabthefish

+0

你怎麼知道問題出在'Where',它不在'Select'中?嘗試分割它們並用調試器檢查。 –

回答

0

問題是基礎數據錯誤。我添加了.Trim(),現在相同的代碼塊按預期工作。

JsonResult jso = Json(ItemList 
      .Where(x => x.ItemName.Trim().Equals(stringItemName)) 
      .Select(x => new { x.Year }).Distinct() 
      .Select(x => new { Text = x.Year.ToShortDateString(), Value = x.ToShortDateString() }));