How to get the first value in Dictionary< string, int > #shorthand

Viewed 48
Dictionary shoppingList = new Dictionary <string, int>()
{
   {"Eggs",200 },
   {"Milk",200},
   {"Fish",400},
   {"Apples",150}
};
2 Answers

Dictionary does not have a concept of "first", and indeed is free to re-order things. Now you can get a .First() item, but it's only guaranteed for that enumeration, and the order might not be the order you expect or want. That said, I'm not aware of a specific case .Net will actually do this; just be aware it's not part of the "contract" for the type.

Really, it seems like what you have here is more of a List<ShoppingItem> (it's even in the name of the variable!), where ShoppingItem is a class with properties for Name and Price.

To be more predictable about retrieving the first item, it might be helpful to create a class called ShoppingItem and then use a List instead of a Dictionary:

public class ShoppingItem
{
    public int Id { get; set; }

    public string Name { get; set; }

    public decimal Price { get; set; }
}

Create a List using your new ShoppingItem type.

List<ShoppingItem> shoppingList = new List<ShoppingItem>();

Populate your list:

shoppingList.Add(
    new ShoppingItem
    {
        Id = 1,
        Name = "Eggs",
        Price = 200
    });

shoppingList.Add(
    new ShoppingItem
    {
        Id = 2,
        Name = "Applies",
        Price = 150
    });

Then, finding the first in the sequence can be achieved in a number of ways:

var firstUsingFirst = shoppingList.First();
var firstUsingIndex = shoppingList[0];
var firstLowestId = shoppingList.Find(item => item.Id == (shoppingList.Min(e => e.Id)));

Each method returns a ShoppingItem object, so get the values of the class properties like:

int firstId = firstUsingFirst.Id

Lots of examples in the documentation here.

Related