[英]C# Access Dictionary value from array
Say, I have an string[]
of undetermined length, and a Dictionary<string, object>
, which contains more Dictionaries of its exact type (or other types, which doesn't matter here).比如说,我有一个未确定长度的
string[]
和一个Dictionary<string, object>
,它包含更多与其确切类型(或其他类型,这在这里无关紧要)的字典。
Now I want to change a value in a Dictionary
in a Dictionary
... in my Dictionary depending on my string array.现在我想根据我的字符串数组更改
Dictionary
中字典中的值...在我的Dictionary
中。
Here's a little Visualisation:这是一个小的可视化:
string[]: { "Human", "Legs", "Walking" }
Dictionary:
↳ Key "Human":
↳ Key "Legs":
↳ Key "Walking"
I wanna set the value of the key "Walking" in this example (lets just say to true
)我想在此示例中设置键“Walking”的值(我们只说
true
)
Now my question is: How do i achive this in C#?现在我的问题是:我如何在 C# 中实现这个目标?
Any answers will be appreciated, please excuse me if i am overthinking this.任何答案将不胜感激,如果我想得太多,请原谅。
Because you're using Object
for TValue
you'll need to use the x is T v
operator to test if an Object
is another dictionary, eg if( x is Dictionary<String,Object> dict )
.因为您将
Object
用于TValue
,所以您需要使用x is T v
运算符来测试Object
是否是另一个字典,例如if( x is Dictionary<String,Object> dict )
。
The difficulty here is that you can't use x is T v
with a strongly-typed T
because IReadOnlyDictionary<K,V>
is not covariant over V
, even when you know what K
is (as C# and .NET do not support partially-closed generic types).这里的困难在于,您不能将
x is T v
与强类型T
一起使用,因为IReadOnlyDictionary<K,V>
不是V
的协变,即使您知道K
是什么(因为 C# 和 .NET 不部分支持 -封闭的泛型类型)。
...but if you don't need/want exactly-typed types and provided that all dictionary objects in your graph are always exactly Dictionary<String,Object>
(and not Dictionary<String,Int32>
or Dictionary<String,String>
) then you can do this: ...但是如果您不需要/不想要完全类型化的类型,并且假设您的图中的所有字典对象始终完全是
Dictionary<String,Object>
(而不是Dictionary<String,Int32>
或Dictionary<String,String>
) 那么你可以这样做:
String[] dictPath = new[] { "Human", "Legs", "Walking" };
Dictionary<String,Object> dictGraph = ...
Object humanLegsWalkingValue = GetValueAtPath( dictGraph, dictPath );
//
static Object? GetValueAtPath( Dictionary<String,Object> root, String[] dictPath )
{
List<String> breadcrumbs = new List<String>(); // For reporting errors.
Dictionary<String,Object> current = root;
foreach( String name in dictPath )
{
breadcrumbs.Add( name );
if( current.TryGetValue( name, out Object? value ) )
{
if( value is Dictionary<String,Object> dict )
{
current = dict;
}
else
{
if( breadcrumbs.Count == dictPath.Length )
{
return value;
}
else
{
String valueType = value is null ? "null" : value.GetType().FullName;
const String MSG_FMT = "Value at \"{0}\" is not a dictionary but is actually {1}, therefore \"{2}\" is unreachable."
throw new InvalidOperationException( String.Format( MSG_FMT, String.Join( ".", breadcrumbs ), valueType, String.Join( ".", dictPath ) ) );
}
}
}
else
{
const String MSG_FMT = "Could not find name \"{0}\" at \"{1}\" therefore \"{2}\" is unreachable."
throw new KeyNotFoundException( String.Format( MSG_FMT, name, String.Join( ".", breadcrumbs ), String.Join( ".", dictPath ) ) );
}
}
}
To set a value, it uses almost the exact same logic to walk the dictionary-graph, except it stops 1-step short of the end of dictPath
and uses that to set an entry in current
:要设置一个值,它使用几乎完全相同的逻辑来遍历字典图,除了它在
dictPath
末尾前停止 1 步并使用它来设置current
中的条目:
static void SetValueAtPath( Dictionary<String,Object> root, String[] dictPath, Object newValue )
{
List<String> breadcrumbs = new List<String>(); // For reporting errors.
Dictionary<String,Object> current = root;
foreach( ( String name, Int32 idx ) in dictPath.Select( ( n, i ) => ( n, i ) ) )
{
breadcrumbs.Add( name );
if( idx == dictPath.Length - 1 )
{
current[ name ] = newValue;
return;
}
else if( current.TryGetValue( name, out Object? value ) )
{
if( value is Dictionary<String,Object> dict )
{
current = dict;
}
else
{
String valueType = value is null ? "null" : value.GetType().FullName;
const String MSG_FMT = "Value at \"{0}\" is not a dictionary but is actually {1}, therefore {2} is unreachable."
throw new InvalidOperationException( String.Format( MSG_FMT, String.Join( ".", breadcrumbs ), valueType, String.Join( ".", dictPath ) );
}
}
else
{
const String MSG_FMT = "Could not find name \"{0}\" at \"{1}\" therefore \"{2}\" is unreachable."
throw new KeyNotFoundException( String.Format( MSG_FMT, name, String.Join( ".", breadcrumbs ), String.Join( ".", dictPath ) ) );
}
}
}
This might not be a (direct) answer to your question:这可能不是您问题的(直接)答案:
string[] strs = new string[] { "Human", "Legs", "Walking" };
Dictionary<string,string> dict = new Dictionary<string, string>();
for(int i=0; i<strs.Length; i++) {
dict.Add(strs[i],(i>0?strs[i-1]:""));
}
string find = "Human";
if(dict.ContainsKey(find)) {
System.Console.WriteLine($"Hello: {find}");
foreach (var item in dict.Where(x=>x.Value==find))
{
System.Console.WriteLine($"You have: {item.Key}");
foreach (var item2 in dict.Where(x=>x.Value==item.Key))
{
System.Console.WriteLine($"Which can make you: {item2.Key}");
}
}
}
else
{
System.Console.WriteLine($"Could not find: {find}");
}
output: output:
Hello: Human
You have: Legs
Which can make you: Walking
NOTE: It's pretty unclear why the title of your question has Dictionary
and you start defining an array ( string[]
).注意:目前还不清楚为什么你的问题的标题有
Dictionary
并且你开始定义一个数组( string[]
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.