سؤال

The following code loops through a list and gets the values, but how would I write a similar statement that gets both the keys and the values

foreach (string value in list.Values)
{
    Console.WriteLine(value);
}

e.g something like this

    foreach (string value in list.Values)
{
    Console.WriteLine(value);
        Console.WriteLine(list.key);
}

code for the list is:

SortedList<string, string> list = new SortedList<string, string>();
هل كانت مفيدة؟

المحلول

foreach (KeyValuePair<string, string> kvp in list)
{
    Console.WriteLine(kvp.Value);
    Console.WriteLine(kvp.Key);
}

From msdn:

GetEnumerator returns an enumerator of type KeyValuePair<TKey, TValue> that iterates through the SortedList<TKey, TValue>.

As Jon stated, you can use var keyword instead of writing type name of iteration variable (type will be inferred from usage):

foreach (var kvp in list)
{
    Console.WriteLine(kvp.Value);
    Console.WriteLine(kvp.Key);
}

نصائح أخرى

Apologies...

this was wrong topic (loop through values). My issue was looping through the key value pairs, not just the values. Will leave this here if there are no objections as a possible option to get values from SortedList collection.

I just tried to figure out this error as well and my solution was to use the DictionaryEntry type to replace the erroring out KeyValuePair type. Found from MS reference https://msdn.microsoft.com/en-us/library/system.collections.dictionaryentry(v=vs.100).aspx

In my case, I had code creating a SortedList type collection and neither the var or KeyValuePair types worked (var errored out when trying to read the key/value from the collection item and the KeyValuePair errored out in the initial loop definition. Both errored out with "Specified cast is not valid" )

So here is sample of code that worked for me:

SortedList _dims = GetList("mysortedlist");
foreach (DictionaryEntry kvp in _dims)
{
    Console.WriteLine(kvp.Key.ToString());
    Console.WriteLine(kvp.Value.ToString()); 
}

HTH

Dave

Just iterated using the keys and get the value for each key:

SortedList<string, string> info = new SortedList<string, string>();

info.Add("path", "път");
info.Add("folder", "директория");
info.Add("directory", "директория");
info.Add("file", "Файл");

foreach (string key in info.Keys)
{
 Console.WriteLine("\t{0}\t{1}", key, info[key]);
}
 bool value = list[key];

this can help you.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top