簡體   English   中英

'將'Dictionary <string,int>轉換為List <object>

[英]'Convert' Dictionary<string,int> into List<object>

我有一個Dictionary<string,int> dictionary1 ,我需要將它轉換為List<Data> ,其中Data具有屬性lable = dictionary1.key和value = dictionary1.value。 我不想使用for / foreach循環(由我自己編寫),因為為了避免它我試圖使用Dictionary。

另一種選擇是擁有兩個不同的詞典(dictionary2和dictionary3),其中dictionary2<string,keyOfDictionary1>dictionary3<string,valueOfDictionary1>

我有道理嗎? 那可能嗎? 有更好的選擇嗎?

假設:

class Data
{
    public string Label { get; set; }

    public int Value { get; set; }
}

然后:

Dictionary<string, int> dic;
List<Data> list = dic.Select(p => new Data { Label = p.Key, Value = p.Value }).ToList();

也許你可以使用LINQ?

dictionary1.Select(p => new Data(p.Key, p.Value)).ToList()

然而,這是使用yield ,因此在后台循環...

myDictionary.Select(x => new Data(){ label = x.Key, value = x.Value).ToList();

我假設“無循環”實際上意味着“我想要LINQ”:

List<Data> = dictionary1.Select(
    pair => new Data() {
        label = pair.Key,
        value = pair.Value
    })).ToList();

嘗試

dictionary1.Select(p => new Data(p.Key, p.Value)).ToList();

.NET已經有一種數據類型可以執行Data操作: KeyValuePair<T1,T2> Dictionary已經實現了IEnumerable<KeyValuePair<T1,T2>> ,只是強制轉換它。

Dictionary<string, int> blah = new Dictionary<string, int>();
IEnumerable<KeyValuePair<string, int>> foo = blah;

這是一個老帖子,但帖子只是為了幫助其他人;)

轉換任何對象類型的示例:

public List<T> Select<T>(string filterParam)
{    
    DataTable dataTable = new DataTable()

    //{... implement filter to fill dataTable }

    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> row;

    foreach (DataRow dr in dataTable.Rows)
    {
        row = new Dictionary<string, object>();
        foreach (DataColumn col in dataTable.Columns)
        {
            row.Add(col.ColumnName, dr[col]);
        }
        rows.Add(row);
    }

    string json = new JavaScriptSerializer().Serialize(rows);

    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
    {
        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T[]));
        var tick = (T[])deserializer.ReadObject(stream);
        return tick.ToList();
    }
}
    public class Data
    {
        public string Key { get; set; }

        public int Value { get; set; }
    }

    private static void Main(string[] args)
    {
        Dictionary<string, int> dictionary1 = new Dictionary<string, int>();
        dictionary1.Add("key1", 1);
        dictionary1.Add("key2", 2);

        List<Data> data = dictionary1.Select(z => new Data { Key = z.Key, Value = z.Value }).ToList();

        Console.ReadLine();
    }

以防萬一只是幫助任何人,我這樣做 - 將處理比單個值類型更復雜的對象,如OP所述。

// Assumes: Dictionary<string, MyObject> MyDictionary;
List<MyObject> list = new List<MyObject>();
list.AddRange(MyDictionary.Values.ToArray());

暫無
暫無

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

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