How can I insert my sortedlist into a listbox?
I am new to C# and currently using a sortedlist<string, int> in order to store values that I need to display in a listbox (according to my uni, this is how I need to do it). I have tried quite a few things however I am struggling to get both the key AND value into a listbox. Would anybody be able to give me some guidance on how I can go about doing this?
32 Replies
listbox in winforms? wpf? web site?
Apologies, it is in winforms
try
or
First one does not contain definitions for all but DataSource
Second one does show my value but not the key
ah lol just noticed its swapped, just swap it
make it show the key instead
lol, now the key is showing but the value is not
that is the point
you want to display both at the same time?
Correct
Ive been able to show one at a time, however been struggling to make it show both
unsure, try removing these lines
Displays the value
hmm, i recall DataSource can accept a list directly
How I originally have been doing it is through .ToList, however that only displays the value
lsbScores.DataSource = scores.ToList();
ok put .ToList() at the end
yourlistBox.DataSource = yourSortedList.Select(x => new KeyValuePair<string,int>($"{x.Key} {x.Value}", x.Value)).ToList();
This works, thank you so much for that...
Ill take some time to understand why it works as well. If I have any questions ill message you if you dont mind?
well thats simple, KeyValuePair has 2 columns, Key and Value
DisplayMember selects which Column to display for the user
Right, but its set to key, so why does it display both the value and key?
it does not
the value is actually concatenated in the key
by this line
yourSortedList.Select(x => new KeyValuePair<string,int>($"{x.Key} {x.Value}", x.Value));
that line is setting x to be key:value correct?
you see, SortedList<string,int> is actually a collection of KeyValuePair<string,int>
Im not suuuper familiar with lambdas yet, so trying to understand that line specifically lol
say u have a key called
Foo
with a value of 1
This I understand
all i did was converting the key to
Foo 1
Yeah, im understanding that
so now the Key of this element is
Foo 1
instead of Foo
it hasnt changed my actual key to foo 1 though right? lol
in the sorted list itself? no
ok cool
Ah I see, ur initializing a new keyvaluepair and setting that to be my sortedlists key+value in the key
right?
yes
coool im understanding then
thanks so much
I appreciate it