How to find key value pair in a dictionary with values > 0 with key matching a certain string pattern?
15,186
Solution 1
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
Solution 2
You can use Enumerable.Where to filter then dictionary elements
var result = oSomeDictionary.Where(c=>c.Key.StartsWith("card") && c.Value > 0)
Solution 3
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);
}
Output will be:
Key: card2, Value: 1
Key: card6, Value: 1
Here is a DEMO
.
Solution 4
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.
Solution 5
Dictionary
implements <IEnumerable<KeyValuePair<TKey,TValue>>
, so you can iterate through it 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]
Author by
user1874589
Updated on July 28, 2022Comments
-
user1874589 almost 2 years
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?