簡體   English   中英

創建通用函數以在C#中將數組轉換為字典

[英]Creating a Generic Function to convert an Array into a Dictionary in C#

我有一個包含兩個公共變量的結構。 我制作了該結構的數組,並希望將其轉換為字典。

這是一種完成該任務的方法:

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;
    }
}

現在,這適用於我的特定設置,但是我希望嘗試將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;
}

您可能會說,我無法訪問我試圖轉換為鍵值對的任何結構數組的公共字段。

這樣,您如何建議我進行通用轉換?

請注意,我的特定設置要求我將結構轉換為字典,因為我正在使用Unity Game Engine。

謝謝。

LINQ中已經實現了執行此操作的通用方法。

var dict = myArray.ToDictionary(a => a.TheKey);

隨着您的實施

public struct KeyValuePairs
{
    public string variableOne;
    public float variableTwo;
}

和一個數組

KeyValuePairs[] keyValuePairs = ...;

你得到

Dictionary<string, KeyValuePairs> dict = keyValuePairs
    .ToDictionary(a => a.variableOne);

或者

Dictionary<string, float> dict = keyValuePairs
    .ToDictionary(a => a.variableOne, a => a.variableTwo);

請注意,第一個變體產生具有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;
}

或者就是這樣,如果您想將項目本身存儲為值

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;
}

您可以使用反射來實現

首先,在變量中添加{get;set;}以將其轉換為屬性

public struct KeyValuePairs
{
    public string variableOne { get; set; }
    public float variableTwo { get; set; }
}

然后的方法

// T1 -> Type of variableOne
// T2 -> Type of variableTwo
// T3 -> KeyValuesPair type
public static Dictionary<T1, T2> convert<T1,T2,T3>(T3[] data)
{
    // Instantiate dictionary to return
    Dictionary<T1, T2> dict = new Dictionary<T1, T2>();

    // Run through array
    for (var i = 0;i < data.Length;i++)
    {
        // Get 'key' value via Reflection to variableOne
        var key = data[i].GetType().GetProperty("variableOne").GetValue(data[i], null);
        // Get 'value' value via Reflection to variableTow
        var value = data[i].GetType().GetProperty("variableTwo").GetValue(data[i], null);
        // Add 'key' and 'value' to dictionary casting to properly type
        dict.Add((T1)key, (T2)value);
    }
    //return dictionary
    return dict;
}

我使用以下代碼進行測試

KeyValuePairs[] val = new KeyValuePairs[5];

val[0] = new KeyValuePairs() { variableOne = "a", variableTwo = 2.4f };
val[1] = new KeyValuePairs() { variableOne = "b", variableTwo = 3.5f };
val[2] = new KeyValuePairs() { variableOne = "c", variableTwo = 4.6f };
val[3] = new KeyValuePairs() { variableOne = "d", variableTwo = 5.7f };
val[4] = new KeyValuePairs() { variableOne = "e", variableTwo = 6.8f };

Dictionary<string, float> dict = convert<string, float,KeyValuePairs>(val);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM