c# - 在 C# 中从字典中过滤键值

标签 c# dictionary filter

我是 C# 的新手,目前正在尝试找出实现以下内容的最佳方法:

我有一个具有相关组的物种列表:

Bird: "Budgie", "Parrot"
Dog: "Pitbull", "Labrador"
Cat: "Cheetah", "Lion"

给定一个动物字符串,我需要返回它的组。 例如。 “猎豹”将返回“猫”。

我已经实现了以下内容:

// create list one and store values
List<string> valSetOne = new List<string>();
valSetOne.Add("Budgie");
valSetOne.Add("Parrot");

// create list two and store values
List<String> valSetTwo = new List<String>();
valSetTwo.Add("Lion");
valSetTwo.Add("Cheetah");

// create list three and store values
List<String> valSetThree = new List<String>();
valSetThree.Add("Labrador");
valSetThree.Add("Pitbull");

// add values into map
map.Add("Bird", valSetOne);
map.Add("Cat", valSetTwo);
map.Add("Dog", valSetThree);

foreach(KeyValuePair<string, List<string>> kvp in map){
    foreach(string value in kvp.Value)
    {
       Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, value);
    }
}

除了使用 foreach 循环,是否有更快的方法来找到给定动物值的键?

//编辑:

目前正在尝试使用元组进行初始化

var tupleList = new List<Tuple<string, List<string>>>
{
   new Tuple<string, List<string>>("cat", { "cheetah", "lion"})

};

我收到以下错误:意外的符号 `{'

最佳答案

更好的数据建模是创建一个组类,其中包含一个名称和一组动物。然后您可以保存一组组并对其进行查询。

如果您想坚持使用字典,那么:由于您的问题是从该键的值列表中检索给定 valuekey,我以相反的方式组织数据:

var map = new Dictionary<string,string>
{
    ["Cheetah"] = "Cat",
    ["Lion"] = "Cat",
    //....
};

然后您可以通过您的真实 key 进行搜索 - 这是物种而不是组:

if(map.TryGetValue("Lion", out var group)) { }

由于通过分组到物种列表更容易构建数据,您可以:

var rawData = new List<(string group, List<string> species)>
{
    ("Cat", new List<string> { "Cheetah", "Lion" }),
    //...
};

var result = rawData.SelectMany(item => item.species.Select(s => (s, item.group)))
                    .ToDictionary(k => k.s, v => v.group);

这适用于 C#7.0 命名元组。如果您使用的是以前的版本,则可以使用匿名类型或“老式”元组

对于 C# 7.0 之前的集合初始化:

var rawData = new List<Tuple<string, List<string>>>
{
    Tuple.Create<string,List<string>> ("Cat", new List<string> { "Cheetah", "Lion" })
};

关于c# - 在 C# 中从字典中过滤键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47661793/

相关文章:

c# - 如何将 Dictionary<TKey, TValue> 的所有值作为 IList<TValue> 获取?

python - 使用给定 key 的文件加密和解密

filter - proguard 多个 injar 到多个 outjar : The output jar must have a filter, 或所有后续输出 jar 将为空

javascript - 使用 JavaScript 过滤 Firebase 查询

c# - Unity Share 脚本 Android 到 iOS

c# - 如何从 DirectoryEntry 和 DN 检索 DirectoryEntry

python - 集合字典中的总和值

javascript - 如何过滤 JSON 对象 (JavaScript)

c# - PetaPoco 集成中的错误

c# - WPF:将ListBox的高度限制为网格行的高度