Reputation: 11931
I have a list I want to map to a Dictionary<string, object>
. The resulting dictionary should look like:
var dictionary = new Dictionary<string, object>{
{ Prop.Name, item.Name },
{ Prop.Address, item.Address}
//other properties
}
I got stuck trying to leverage the Linq query below:
var dict = myList.Select((h, i) => new { key = h, index = i })
.ToDictionary(o => o.key, o => values[o.index]));
And...
foreach(var item in list){
var _dict = new Dictionary<string, object>{
{Prop.Name, item.Name},
//other properties
}
}
How can I map myList
and return a dictionary like the one above? Is there a better way?
Upvotes: 0
Views: 1617
Reputation: 7054
From your examples I see that you want map each item of list to Dictionary. Please try this code:
var commonProps = typeof(CommonProperty).GetProperties(BindingFlags.Static | BindingFlags.Public);
var itemProps = list.GetType().GenericTypeArguments[0].GetProperties().ToDictionary(k => k.Name, v => v);
var result = list.Select(l => commonProps.ToDictionary(
k => k.GetValue(null),
v => itemProps[v.Name].GetValue(l)
));
Upvotes: 1
Reputation: 139
What exactly do you mean by "Both key and value are of the same 'names'"? If keys you want in the dicrionary match property names in an item then you can use reflection as follows:
item.GetType().GetProperties().ToDictionary(x => x.Name, x => x.GetValue(item));
This example does not filter by CommonProperty which can results in extra entries in the dictionary if item has any properties you are not interested in.
The following is the complete example program which displays properties of all files in a directory:
static class Program
{
static Dictionary<string, object> ObjToDic(object o)
{
return o.GetType().GetProperties().ToDictionary(x => x.Name, x => x.GetValue(o));
}
static void Main(string[] args)
{
var fileNames = Directory.EnumerateFiles("c:\\windows");
foreach (string name in fileNames)
{
Console.WriteLine("==========================================");
FileInfo fi = new FileInfo(name);
var propDict = ObjToDic(fi); // <== Here we convert FileInfo to dictionary
foreach (var item in propDict.AsEnumerable())
{
Console.WriteLine(string.Format("{0}: {1}", item.Key, item.Value.ToString()));
}
}
}
}
Bear in mind that in .NET there are properties and fields. Both are read and written using the same syntax in C#, but reflection handles them differently. The example above displays only properties.
Upvotes: 1