Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find key value pair in a dictionary with values > 0 with key matching a certain string pattern?

This is a dictionary,

Dictionary<string, uint> oSomeDictionary = new Dictionary<string, uint>();

oSomeDictionary.Add("dart1",1);
oSomeDictionary.Add("card2",1);
oSomeDictionary.Add("dart3",2);
oSomeDictionary.Add("card4",0);
oSomeDictionary.Add("dart5",3);
oSomeDictionary.Add("card6",1);
oSomeDictionary.Add("card7",0);

How to get the key/value pairs from oSomeDictionary with keys that starts with string "card" and has value greater than zero?

like image 409
user1874589 Avatar asked Apr 01 '13 10:04

user1874589


1 Answers

var result = oSomeDictionary.Where(r=> r.Key.StartsWith("card") && r.Value > 0);

for output:

foreach (var item in result)
{
    Console.WriteLine("Key: {0}, Value: {1}", item.Key, item.Value);
}

output:

Key: card2, Value: 1
Key: card6, Value: 1

Remember to inlcude using System.Linq

like image 156
Habib Avatar answered Nov 16 '22 23:11

Habib