2012-03-28 41 views
0

答案在編輯解決以下的LinQ相關,從Dictionary對象

濾波結果我有這樣一段代碼

Dictionary<Merchant, int> remaingCards = CardService.GetRemainingCardsNumber(int.MaxValue, 0).Result; 

GetRemainingCardsNumber返回客商Id和Name屬性,並匹配卡對象數字爲Int。

現在,假設我想過濾基於Merchant對象內的Name屬性的字典。我這樣做:

cardmodel.MerchantRemainingCards = from Dictionary<Merchant, int> filterRemaining in cardserv.GetRemainingCardsNumber(int.MaxValue, 0).Result 
                where filterRemaining.Keys.FirstOrDefault().Name.Contains(merchantNameFilter) 
                select filterRemaining; 

但顯然它不工作,因爲我不熟悉字典類型。

- 解決在這裏 -

 cardmodel.MerchantRemainingCards = cardserv.GetRemainingCardsNumber(int.MaxValue, 0).Result 
              .Where(e => e.Key.Name.ToLower().Contains(merchantNameFilter.ToLower())) 
              .ToDictionary(e => e.Key, e => e.Value); 

只需將它轉換回字典。

+1

一個很好的_become_熟悉的方式字典類型是閱讀文檔:[Dictionary ](http://msdn.microsoft.com/en-us/library/xfhwa508.aspx) – 2012-03-28 03:54:33

回答

4

如果,你的建議,你的代碼第一位不返回Dictionary,那麼你應該能夠做到這一點:

from KeyValuePair<Merchant, int> card in cardserv.GetRemainingCardsNumber(int.MaxValue, 0).Result 
where card.Key.Name.Contains(merchantNameFilter) 
select card; 
+0

cardmodel.MerchantRemainingCards本身是一本字典,我該如何將KeyValuePair轉換回字典? – user777310 2012-03-28 04:04:35

+0

你不知道。但你所擁有的是一個'IEnumerable ',你可以使用'.ToDictionary()'方法將其轉換爲'Dictionary'。 – 2012-03-28 04:38:58

0

可能的替代

var remaingCards = cardserv.GetRemainingCardsNumber(int.MaxValue, 0).Result.SelectMany(x => x.Keys).Where(x => x.Name.Contains(merchantNameFilter));