2012-03-28 43 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));