简体   繁体   中英

Multidimensional List Binding to Listbox

I know how to bind a list to a listbox but I created a multidimensional list with the below code but cannot figure out how to bind it to a listbox.

public class MultiDimDictList<K, T> : Dictionary<K, List<T>>
    {
        public void Add(K key, T addObject)
        {
            if (!ContainsKey(key)) Add(key, new List<T>());
            base[key].Add(addObject);
        }
    }

And then the below to utilize this class and add 2 strings to the list:

var myDicList = new MultiDimDictList<string, string>();
        myDicList.Add("Title", "Data");
        myDicList.Add("Title2", "Data2");

Basically what I am trying to do is bind this data to a listbox showing only the title's but then when a button is clicked it uses the data portion to complete the process.

I am not sure where to go with this as I have been looking at other posts but haven't found anything similar to what I am trying to do.

Thanks for any help.

A Dictionary<K,V> is not a list. The titles in your case are the keys of the dictionary and those are not sorted. You can access them through the Keys property but would have to sort them before binding. Add this property to your MultiDimDictList

public List<string> Titles { get { return Keys.OrderBy(k => k).ToList(); } }

and bind the listbox to this property.

The example above assumes that the keys are of string type. When using the generic type parameter K you have to convert to string first (unless you want a list of K of cause):

public List<string> Titles {
    get {
        return Keys
            .Select(k => k.ToString())
            .OrderBy(s => s)
            .ToList(); 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM