I have Following Array an want to sort it by the time key:
Dictionary<string, object>[] callHistory = CharactersPhone.CharactersPhoneCallHistorys_.ToList().Where(x => x.charPhoneNumber == Characters.GetCharacterPhonenumber(charId)).Select(x =>
new Dictionary<string, object>
{
{"charPhoneNumber" , x.charPhoneNumber.ToString()},
{"targetPhoneNumber" , x.targetNumber.ToString()},
{"state" , x.state},
{"outgoingstate", x.outgoingState},
{"time" , x.timestamp.ToString("dd.MM.yyyy HH:mm")}
}).ToArray();
I try it with the following:
var sorted = callHistory.OrderBy(x => Array.IndexOf(callHistory, x.time))
but the key "x.time" is not found, i think i have a little brain lag here or something is fundamental wrong but i doesnt find the answer. Maybe someone here can help.
CodePudding user response:
For dictionaries you need to use the indexer:
var sorted = callHistory.OrderBy(x => x["time"])
I would also note that this sorts it by the string values since that's what you use to create the dictionary. I would either keep it as a time and only convert to string when you display the data, or store the date/time in a sortable format (e.g. yyyy-MM-dd hh:mm
)
CodePudding user response:
You're trying to access a keyed
value as though it were a property
or field
.
Instead of accessing it with the .
operator, use the index operator
, as shown below:
var a = new Dictionary<string, object>
{
{"charPhoneNumber" , 'a'},
{"targetPhoneNumber" , 'b'},
{"state" , 'c'},
{"outgoingstate", 'd'},
{"time" , 'e'}
};
var b = a["time"];
Console.WriteLine(b); // Outputs "e"
In your case, you'd use x["time"]
in place of x.time
.