How to make a list dictionary using dynamic key in C #

I am working on a program in which I need to create a dictionary in which I will pass a string and a list at runtime, and he must create a dictionary using this string as a key property.

below is the class:

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

here is the function

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

}

I have an idea that this can be done using reflection, but I don't know how to do it.

+4
source share
3 answers

I got a solution, thanks for the help :)

this is the desired code

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);
}
0
source

Assuming you have List<Tour>a variable with a name tours, you can get it Dictionary<int, Tour>like this:

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

Link
Enumerable.ToDictionary<TSource, TKey> Method

+1

,

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));
}
0
source

All Articles