如果值包含字符串,获取字典键

本文关键字:获取 字典 字符串 包含 如果 | 更新日期: 2023-09-27 18:06:47

我有这本字典:

    static Dictionary<int, string> Players = new Dictionary<int, string>();
    dictionary.Add(1, "Chris [GC]");
    dictionary.Add(2, "John");
    dictionary.Add(3, "Paul");
    dictionary.Add(4, "Daniel [GC]");

我想获得包含"[GC]"的值的键

知道怎么做吗?

谢谢。

如果值包含字符串,获取字典键

使用LINQ:

var result = Players.Where(p => p.Value.Contains("[GC]")).Select(p => p.Key);

使用如下查询:

   var itemsWithGC = dictionary.Where(d => d.Value.Contains("[GC]")).Select(d => d.Key).ToList();
   foreach (var i in itemsWithGC)
   {
       Console.WriteLine(i);
   }

实际上有一个更高效的方法来解决这个问题,但它可能需要一些重构…

当你添加一个包含"[GC]"的新球员时,你可以填充一个HashSet<int>:

Dictionary<int, string> Players = new Dictionary<int, string>();
HashSet<int> gcPlayers = new HashSet<int>();
dictionary.Add(1, "Chris [GC]");
gcPlayers.Add(1);
dictionary.Add(2, "John");
dictionary.Add(3, "Paul");
dictionary.Add(4, "Daniel [GC]");
gcPlayers.Add(4);

所以现在获得所有包含"[GC]"的键就像使用整个集合称为gcPlayers一样简单。

这将避免查询并迭代整个字典以获得所有巧合,同时您将避免向gcPlayers添加重复项,因为它是一个集合(即是唯一值的无序集合)