C# C、 C语言中的Linq搜索字典并使用键返回字符串
我创建了一本字典C# C、 C语言中的Linq搜索字典并使用键返回字符串,c#,string,linq,dictionary,C#,String,Linq,Dictionary,我创建了一本字典 Dictionary<string, string> delta = new dictionary<string, string>(); delta.Add("A", "One"); delta.Add("B", "Two"); delta.Add("C", "Three"); 我想根据作为键传递的值检索值 public string GetValuefromdictionary(string roll.
Dictionary<string, string> delta = new dictionary<string, string>();
delta.Add("A", "One");
delta.Add("B", "Two");
delta.Add("C", "Three");
我想根据作为键传递的值检索值
public string GetValuefromdictionary(string roll. Dictionary<string, string> delta)
{
string rollValue;
return rollValue = delta
.Where(d => d.Key.Contains(roll))
.Select(d => d.Value)
.ToString();
}
然而,我看到它没有返回字符串,我得到了这样的结果
System.Linq.Enumerable+其中SelectEnumerableInterator``2[System.Collections.Generic.KeyValuePair``2[System.String,System.String],System.String]
任何帮助如果一个键是ABC,并且您传递了一个as roll,并且您希望从ABC返回值,因为ABC包含a。您可以执行以下操作:
return delta.FirstOrDefault(d=> d.Key.Contains(roll)).Value;
您希望在字典中搜索元素,但使用value而不是>键。因此,您迭代字典并返回
具有您要查找的值的第一个元素。您需要的输出
get是一个键值对,因此是.Key
两种选择,最好是两种情况 案例1 假设字典值是唯一的,在这种情况下,我们可以简单地转置字典交换对 现在我们可以像其他字典一样访问它
transformDictionary["One"];
案例2:
值不是唯一的,在这种情况下使用查找
var lookup = delta.ToLookup(c=>c.Value, c=>c.Key);
var lookupvalue = ((IEnumerable<string>)lookup["One"]).First();
工作基于作为键传递的值的值不清楚,我认为您搜索的是返回增量[roll];若要通过键获取值,则应使用[]运算符。delta[A]返回的值对于单个字符串没有意义。也许你想找到滚动值中包含该字母的值?字典值是唯一的吗?请解释为什么你的代码片段回答了“为什么拒绝投票”的问题?请说明原因,答案有待改进。
transformDictionary["One"];
var lookup = delta.ToLookup(c=>c.Value, c=>c.Key);
var lookupvalue = ((IEnumerable<string>)lookup["One"]).First();