Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a SortedList, getting both the key and the value

Tags:

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>(); 
like image 431
Wayneio Avatar asked Dec 23 '12 17:12

Wayneio


People also ask

In what way SortedList will add the values?

The SortedList<int, string> will store keys of int type and values of string type. The Add() method is used to add a single key-value pair in a SortedList . Keys cannot be null or duplicate.

How to access SortedList in c#?

The SortedList class represents a collection of key-and-value pairs that are sorted by the keys and are accessible by key and by index. A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index.

Can sorted list have duplicate values?

A SortedList does not allow duplicate keys. Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting. Elements in this collection can be accessed using an integer index.

What is SortedList c#?

In C#, SortedList is a collection of key/value pairs which are sorted according to keys. By default, this collection sort the key/value pairs in ascending order. It is of both generic and non-generic type of collection. The generic SortedList is defined in System.


1 Answers

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); } 
like image 90
Sergey Berezovskiy Avatar answered Sep 21 '22 01:09

Sergey Berezovskiy