Jam*_*ill 1 c# arrays generics dictionary unity-game-engine
我有一个包含两个公共变量的结构.我已经创建了该结构的数组,并希望将其转换为Dictionary.
这是一种实现这种方法的方法:
public class TestClass
{
public struct KeyValuePairs
{
public string variableOne;
public float variableTwo
}
private KeyValuePairs[] keyValuePairs;
private Dictionary<string, float> KeyValuePairsToDictionary()
{
Dictionary<string, float> dictionary = new Dictionary<string, float>();
for(int i = 0; i < keyValuePairs.Length; i++)
{
dictionary.Add(keyValuePairs[i].variableOne, keyValuePairs[i].variableTwo);
}
return dictionary;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,这适用于我的特定设置,但我希望尝试将该KeyValuePairsToDictionary()函数转换为Generic,以便它可以适用于所有类型.
那么我的第一个想法是做这样的事情:
private Dictionary<T, T> ArrayToDictionary<T>(T[] array)
{
Dictionary<T, T> keyValuePairs = new Dictionary<T, T>();
for(int i = 0; i < array.Length; i++)
{
keyValuePairs.Add(array[i], array[i]); //The problem is right here.
}
return keyValuePairs;
}
Run Code Online (Sandbox Code Playgroud)
你可能会说,我无法访问我试图转换为键值对的任何结构数组的公共字段.
有了这个,你会怎么建议我去执行通用转换?
请注意,我的特定设置要求我将结构转换为字典,因为我使用的是Unity游戏引擎.
谢谢.
执行此操作的一般方法已在LINQ中实现.
var dict = myArray.ToDictionary(a => a.TheKey);
Run Code Online (Sandbox Code Playgroud)
随着你的实施
public struct KeyValuePairs
{
public string variableOne;
public float variableTwo;
}
Run Code Online (Sandbox Code Playgroud)
和一个数组
KeyValuePairs[] keyValuePairs = ...;
Run Code Online (Sandbox Code Playgroud)
你得到
Dictionary<string, KeyValuePairs> dict = keyValuePairs
.ToDictionary(a => a.variableOne);
Run Code Online (Sandbox Code Playgroud)
或者
Dictionary<string, float> dict = keyValuePairs
.ToDictionary(a => a.variableOne, a => a.variableTwo);
Run Code Online (Sandbox Code Playgroud)
请注意,第一个变量生成一个值为type的字典KeyValuePairs,而第二个变量生成类型的值float.
根据谈话,您似乎对如何实现这一点感兴趣.这是一个建议:
public static Dictionary<TKey, TValue> ToDictionary<T, TKey, TValue>(
this IEnumerable<T> source,
Func<T, TKey> getKey,
Func<T, TValue> getValue)
{
var dict = new Dictionary<TKey, TValue>();
foreach (T item in source) {
dict.Add(getKey(item), getValue(item));
}
return dict;
}
Run Code Online (Sandbox Code Playgroud)
或者简单地说,如果您想将项目本身存储为值
public static Dictionary<TKey, T> ToDictionary<T, TKey>(
this IEnumerable<T> source,
Func<T, TKey> getKey
{
var dict = new Dictionary<TKey, T>();
foreach (T item in source) {
dict.Add(getKey(item), item);
}
return dict;
}
Run Code Online (Sandbox Code Playgroud)