LinQ相关,从Dictionary对象中过滤结果

时间:2012-03-28 03:48:55

标签: c# linq

在下面的编辑中解答了

我有这段代码

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

GetRemainingCardsNumber返回具有Id和Name属性的Merchants对象,匹配的卡号为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); 

把它扔回字典。

2 个答案:

答案 0 :(得分:4)

如果按照您的建议,您的第一段代码确实返回Dictionary,那么您应该可以执行此操作:

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

答案 1 :(得分:0)

可能的替代方案

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