如何在具有值的字典中查找键值对>;0,键与某个字符串模式匹配

本文关键字:gt 模式匹配 字符串 键值对 查找 字典 | 更新日期: 2023-09-27 18:06:54

这是一本字典,

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中获取密钥/值对?

如何在具有值的字典中查找键值对>;0,键与某个字符串模式匹配

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

您可以使用Enumerable。在哪里过滤字典元素

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

您可以使用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

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

上面的完整工作代码。

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]