Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over this particular type of Dictionary<int, Result>?

Tags:

c#

.net

I have a bunch of results from the Database that I keep in a Dictionary<int, Result>().

The Result class I have is:

public int Id { get; set; }
public string something { get; set; }
public string somethingtwo { get; set; }
public string somethingthree { get; set; }
public DateTime Posted { get; set; }
public string Location { get; set; }
public bool somethingfour { get; set; }

So, the Dictionary<int, Result> has many Results inside and I'd like to iterate over them. How an I do this? I've tried a few ways, but even I knew they wouldn't work.

I would like to do something like this:

foreach(var result in resultDict)
{
   mynewstring = result.Location;
   mynewstringtwo = result.Posted;
   // etc etc.
}
like image 669
Arrow Avatar asked Dec 16 '22 23:12

Arrow


1 Answers

foreach(var kvp in resultsDict) {
    //Do somethign with kvp
    UseResult(kvp.Value); //kvp.Value is a Result object
    UseKey(kvp.Key); //kvp.Key is the integer key you access it with
}

In the above code kvp is a KeyValuePair<int, Result>. You can access the Key and Value properties to get the integer key of the Dictionary and the Result value associated with that Key. I'll leave it as an excercise/guessing game for you to figure out which property is which! ;-)

As @Wiktor mentions, you can also access the dictionary's Values and Keys collections to do the same thing, but retrieve a sequence of int or Value properties instead.

Alternatives using the other collections:

foreach(var val in resultsDict.Values) {
    // The key is not accessible immediately,
    // you have to examine the value to figure out the key
    UseResult(val); //val is a value.
}

foreach(var key in resultsDict.Keys) {
    //The value isn't directly accessible, but you can look it up.
    UseResult(resultsDict[key]);
    UseKey(key);
}
like image 134
Chris Pfohl Avatar answered Dec 28 '22 11:12

Chris Pfohl