簡體   English   中英

如何在c#中使用動態鍵創建列表字典

[英]how to make dictionary of a list using dynamic key in c#

我正在編寫一個程序,我需要創建一個字典,我將在運行時傳遞一個字符串和一個列表,它必須使用該字符串作為鍵屬性創建一個字典。

以下是班級:

public class Tour
{
    public int Id{get;set;}
    public string Name{get;set;}
    public string City{get;set;}
}

這是功能

public Dictionary<int,object> GetDictionary(string KeyName, List<object>)
{

}

我有一個想法,它可以使用反射完成,但我不知道如何做到這一點

假設你在一個名為tours的變量中有一個List<Tour> ,你可以得到一個Dictionary<int, Tour>如下所示:

var dictionary = tours.ToDictionary(k => k.Id);

參考
Enumerable.ToDictionary<TSource, TKey> Method

我得到了解決方案,謝謝你的幫助:)

這是所需的代碼

public class Tour
{
    public int Id{get;set;}
    public string Name{get;set;}
    public string City{get;set;}
}

public Dictionary<int,object> GetDictionary(string KeyName, List<object> list)
{
    var dictionary  = Dictionary<int,object>();
    foreach(var obj in list>
    {
         dictionary.Add(GetPropValue(obj,KeyName);
    }
    return dictionary;
}

public object GetPropValue(object src, string propName)
{
     return src.GetType().GetProperty(propName).GetValue(src, null);
}

使用以下命令返回對象內的類型值

public static int GetPropValue(object src, string propName)
{
    return (int)src.GetType().GetProperty(propName).GetValue(src, null);
}

然后只需轉換每個元素並獲取鍵值並使用ToDictionary並在lamda表達式中調用此函數。

public Dictionary<int, object> GetDictionary(string KeyName, List<object> list)
{
    return list.ToDictionary(v => GetPropValue(v, KeyName));
}

暫無
暫無

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

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