Konstantin  Mokhov
Konstantin Mokhov

Reputation: 127

Trying to get the minimum value from a dictionary

I have a dict and variable:

Dictionary<int, string> minDict = new Dictionary<int, string>();
decimal min;

Then dict is filled with the values...

I trying to get the first value and compare with the others:

min = Convert.ToDecimal(minDict.Values.First());
foreach (KeyValuePair<int, string> kvp in minDict)
{
    if (Convert.ToDecimal(kvp.Value[kvp.Key]) < min)
        min = Convert.ToDecimal(kvp.Value[kvp.Key]);
}

But I have an error, when compare variables (<) Invalid cast from 'Char' to 'Decimal'.

Upvotes: 0

Views: 3789

Answers (3)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

You are already iterating over key-value pairs so you don't need to use the indexer:

min = Convert.ToDecimal(minDict.Values.First());
foreach (KeyValuePair<int, string> kvp in mininDict)
{
    if (Convert.ToDecimal(kvp.Value) < min) min = Convert.ToDecimal(kvp.Value);
}

Also here's how you can do it with LINQ:

var min = minDict.Select(item => Convert.ToDecimal(item.Value)).Min();

Upvotes: 4

BlackBear
BlackBear

Reputation: 22979

decimal min = minDict.Values.Select(s => Convert.ToDecimal(s)).Min();

Upvotes: 3

nvoigt
nvoigt

Reputation: 77294

kvp.Value[kvp.Key]

This does not make sense. kvp.Value already is the value. If you only use kvp.Value without the indexer, it should work.

Upvotes: 1

Related Questions