如何在字典中查找值为>的键值对0与键匹配某个字符串模式?

时间:2013-04-01 10:24:58

标签: c# linq 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);

如何使用以字符串“card”开头且值大于零的键从oSomeDictionary获取键/值对?

5 个答案:

答案 0 :(得分:10)

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

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

输出:

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

请记得加入using System.Linq

答案 1 :(得分:3)

您可以使用Enumerable.Where过滤字典元素

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

答案 2 :(得分:2)

您可以使用IEnumerable.Where()String.StartsWith()等方法;

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);
}

输出将是:

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

这是DEMO

答案 3 :(得分:2)

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();
        }
   }

上面的完整工作代码。

答案 4 :(得分:1)

Dictionary实现<IEnumerable<KeyValuePair<TKey,TValue>>,因此您可以使用简单的LINQ扩展方法迭代它

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

Console.WriteLine (string.Join(Environment.NewLine, pairs));

打印:

[card2, 1]
[card6, 1]