user777310
user777310

Reputation: 215

LinQ related , filtering result from a Dictionary Object

Answer solved in edit below

I had this piece of code

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

GetRemainingCardsNumber returns Merchants object with Id and Name property , and the matching card numbers as Int .

Now , let say I want to filter the dictionary based on the Name property inside the Merchant object . I did it like this :

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

But obviously its not working because I'm not familiar with dictionary type .

-- solved it here --

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

Just cast it back to dictionary .

Upvotes: 0

Views: 287

Answers (2)

weeyoung
weeyoung

Reputation: 172

possible alternative

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

Upvotes: 0

Andrew Cooper
Andrew Cooper

Reputation: 32576

If, as you suggest, your first bit of code does return a Dictionary then you should be able to do this:

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

Upvotes: 4

Related Questions