How to find a pair of key values ​​in a dictionary with values> 0 with a key matching a specific 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 key / value pairs from oSomeDictionary with keys starting with a string "map" and having a value greater than zero?

+7
source share
5 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); } 

exit:

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

Remember to enable using System.Linq

+10
source

You can use Enumerable.Where to filter and then dictionary items

 var result = oSomeDictionary.Where(c=>c.Key.StartsWith("card") && c.Value > 0) 
+3
source

You can use IEnumerable.Where() and String.StartsWith() methods like:

 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); var yourlist = oSomeDictionary.Where(n => n.Key.StartsWith("card") && n.Value > 0); foreach (var i in yourlist) { Console.WriteLine("Key: {0}, Value: {1}", i.Key, i.Value); } 

The output will be:

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

Here is the DEMO .

+2
source
 class Program { private static void Main(string[] args) { 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); var result = oSomeDictionary.Where(pair => pair.Key.StartsWith("card") && pair.Value > 0 ); foreach (var kvp in result) { Console.WriteLine("{0} : {1}",kvp.Key,kvp.Value); } Console.ReadLine(); } } 

Full working code above.

+2
source

Dictionary implements <IEnumerable<KeyValuePair<TKey,TValue>> , so you can iterate using simple LINQ extension methods

 var pairs = oSomeDictionary.Where(pair => pair.Key.StartsWith("card") && pair.Value > 0); Console.WriteLine (string.Join(Environment.NewLine, pairs)); 

prints:

 [card2, 1] [card6, 1] 
+1
source

All Articles