简体   繁体   中英

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>> { };

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
}

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.

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)
{
    ...
}

试试这个代码。

headINFO.FirstOrDefault();

Try this:

    int c=0;

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

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