How to retrieve first row from dictionary in C#?

How to retrieve first row from this dictionary. I put around some 15 records.

Dictionary<string, Tuple<string, string>> headINFO = 
                                   new Dictionary<string, Tuple<string, string>> { };

Upvotes: 0

Views: 3355

Answers (5)

eandersson
eandersson

Reputation: 26352

You can use headINFO.First(), but unless you know that there always will be at least one entry in headINFO I would recommend that you use headINFO.FirstOrDefault().

More information on the differences between the two available here.

Edit: Added simple examples

Here is a quick example on how to use FirstOrDefault()

var info = headINFO.FirstOrDefault().Value;
Console.WriteLine(info.Item1); // Prints Tuple item1
Console.WriteLine(info.Item2); // Prints Tuple item2

If you want to print multiple items you can use Take(x). In this case we will loop through three dictionary items, but you can easily modify the number to grab more items.

foreach (var info in headINFO.Take(3))
{
    Console.WriteLine(info.Value.Item1);
    Console.WriteLine(info.Value.Item2);
}

You should also keep in mind that the above foreach does not allow you to modify the values of your Dictionary entries directly.

Edit2: Clarified usage of First() and added clean foreach example

Keep in mind that while First() and FirstOrDefault() will provide you with a single item it does in no way guarantee that it will be the first item added.

Also, if you simply want to loop through all the items you can remove the Take(3) in the foreach loop mentioned above.

foreach (var info in headINFO)
{
    Console.WriteLine(info.Key);          // Print Dictionary Key
    Console.WriteLine(info.Value.Item1);  // Prints Turple Value 1
    Console.WriteLine(info.Value.Item2);  // Prints Turple Value 2
}

Upvotes: 7

Esha Garg
Esha Garg

Reputation: 144

Try this code.

headINFO.FirstOrDefault();

Upvotes: 2

Dilshod
Dilshod

Reputation: 3311

Try this:

    int c=0;

    foreach(var item in myDictionary)
    {
         c++;
         if(c==1)
         {
             myFirstVar = item.Value;
         }
         else if(c==2)
         {
             mySecondVar = item.Value;
         }
          ......
    }

Upvotes: -1

p.s.w.g
p.s.w.g

Reputation: 149020

The easiest way is just to use Linq's First extension method:

var firstHead = headINFO.First();

Or if you want to be safer, the FirstOrDefault method will return null if the dictionary is empty:

var firstHead = headINFO.FirstOrDefault();

If you'd like to loop through all items in the dictionary, try this:

foreach(var head in headINFO)
{
    ...
}

Upvotes: 3

SLaks
SLaks

Reputation: 887453

Dictionaries are unordered, so there is no way to retrieve the first key-value pair you inserted.

You can retrieve an item by calling the LINQ .First() method.

Upvotes: 5

Related Questions