I have an object List<T>
and a keyfieldName of Type T
i am trying to convert this List<T>
to an Dictionary<string,double>
for example if Type T is of type Person, i will be given keyfieldName ="UserId"
ListItem1==> Person
UserId 1
Firstname : "John"
Lastname "Doe"
ListItem2==> Person
UserId 2
Firstname : "Mark"
Lastname "Twain"
ListItem3==> Person
UserId 27
Firstname : "Hello"
Lastname "Life"
the result I am expecting would be Dictionary<string,double>
, idea is take each property in Type T
take its value and append it with :keyfieldName. keyfieldName by itself is excluded from dictionary. All of the property inside Type T
would have to be converted to string.
Dictionary should look like this:
"John:1",0
"Doe:1",0
"Mark:2",0
"Twain:2",0
"Hello:27",0
"Life:27",0
What I have tried so far is to loop:
FieldInfo Idfield = typeof(T).GetField(HashKeyFieldName);
foreach (var item in indexItems)
{
string keyvalue = Idfield.GetValue(item).ToString();
foreach (var f in typeof(T).GetFields().Where(f => f.Name != HashKeyFieldName))
{
string obj =f.GetValue(item).ToString() + ":" + keyvalue;
}
}
I noticed that List
has ToDictionary
function; I was wondering if it can be done faster and better, and if so, how?
If you know the type in advance, I'd just use:
var dictionary = list.Select(x => x.FirstName + ":" + x.UserId)
.Concat(list.Select(x => x.LastName + ":" + x.UserId))
.ToDictionary(p => p, p => 0);
There'll be one extra Concat
call per additional property, but that shouldn't be too bad - again, if you know the class in advance. If you really need to do this with reflection, then the code you've got already is roughly what I'd use - although I'd strongly advise you to use properties rather than fields.
See more on this question at Stackoverflow