2014-01-14 28 views
1

我有下面的代碼的GroupBy我的表並選擇基於模型名計數: -無法趕上如果列表項名稱丟失

var IT360Counts = entities.Resources.Where(a => String.IsNullOrEmpty(a.ASSETTAG) && (a.SystemInfo.ISSERVER == true)) 
    .GroupBy(a => a.SystemInfo.MODEL.ToLower()) 
    .Select(g => new 
    { 
     Action = g.Key.ToLower(), 
     ItemCount = g.Count() 
    }).ToLookup(a => a.Action); 

那麼我會referecne VaR的內容,如: -

IT360RouterNo = IT360Counts["router"] == null ? 0 : IT360Counts["router"].SingleOrDefault().ItemCount, 

上面的方法很好,除非第一個查詢沒有任何路由器,那麼第二個語句將總是返回null異常。所以我的問題是天氣有一種方法來捕捉IT360Counts [「路由器」]存在嗎?

感謝

回答

1

IT360Counts["router"]不是null這會發生,但一個空列表。在這種情況下,IT360Counts["router"].SingleOrDefault()將返回null,因此在訪問其ItemCount屬性時,您將得到一個空例外。

發生這種情況是因爲找不到密鑰時Lookup中的索引器返回空列表。見remarks section in msdn。嘗試檢查查找是否包含密鑰IT360Counts.Contains("router")。這樣,你可以這樣做:

IT360RouterNo = IT360Counts.Contains("router") ? IT360Counts["router"].SingleOrDefault().ItemCount : 0, 

作爲一個側面說明,你還用的ToDictionary代替ToLookup考慮?字典鍵將是您的操作和值ItemCount,因此當檢索值時,您只需在字典中獲得像"router"這樣的鍵的值。如果你一直在做.SingleOrDefault().ItemCount從來沒有期望多個項目具有相同的行動,你可能會更好地使用字典。

完成的緣故這種想法是:

var IT360Counts = entities.Resources.Where(a => String.IsNullOrEmpty(a.ASSETTAG) &&(a.SystemInfo.ISSERVER == true)) 
          .GroupBy(a => a.SystemInfo.MODEL.ToLower()) 
          .Select(g => new 
          { 
           Action = g.Key.ToLower(), 
           ItemCount = g.Count() 
          }).ToDictionary(a => a.Action, a => a.ItemCount); 

IT360RouterNo = IT360Counts.ContainsKey("router") ? IT360Counts["router"] : 0, 

希望它能幫助!

+0

爲了完美,你的幫助很棒.. –