7

这是一本字典,

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

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

4

5 回答 5

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

于 2013-04-01T10:26:32.707 回答
3

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

var result = oSomeDictionary.Where(c=>c.Key.StartsWith("card")  && c.Value > 0)
于 2013-04-01T10:26:52.943 回答
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.

于 2013-04-01T10:27:47.023 回答
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();
        }
   }

上面的完整工作代码。

于 2013-04-01T10:35:56.877 回答
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]
于 2013-04-01T10:27:23.897 回答