Randomly pick key from dictionary weighted by the keys value I was trying to write a function that would get a random card from a dictionary of cards in a players deck weighted by the number of cards of each type you have.
I don't know if the solution I came up with is the fates way of doing something like this and this is something I'm going to be doing a lot per turn because of certain mechanics in the games design. Please let me know if there is something i missed that could help the performance of this code.

For some contexts _deck._card is a dictionary with the key being a string and the value being a int. Dictionary&lt;string, int&gt; _cards

Also Nez.Random is a singleton of my random class for the project. Random.nextInt(int max) takes in a int for the max value of the random number.

static public int nextInt( int max )
{
    return random.Next( max );
}


Code:

public string GetRandomCard()
{
    string result = "";
    var totalWeight = 0;

    foreach (var cardNumber in _deck._cards)
        totalWeight += cardNumber.Value;

    var randNumber = Nez.Random.nextInt(totalWeight);

    foreach (var cardNumber in _deck._cards)
    {
        var value = cardNumber.Value;

        if (randNumber &gt;= value)
        {
            randNumber -= value;
        }
        else
        {
            result = cardNumber.Key;
            break;
        }
    }
    return result;
}


Time complexity O(N^2)
I dont think there is a way to decrease the time complexity but there might be other ways to optimize this code.
After all this good discussion It looks like this function is as optimize as its going to get for its intended purpose. 
I want to note that I was incorrect in its time complexity. The time complexity is actually O(N) not O(N^2) luckily.

Considering this algorithm can perform 1,000 random selections in 0.00194s on a mid range workstation It shouldn't have any performance impact if used many times.

Here are the results of the unit test:

Running random 100 times: 0.0013367s
Key: 30%, Value: 35
Key: 60%, Value: 60
Key: 10%, Value: 5

Running random 1000 times: 0.0019477s
Key: 30%, Value: 378
Key: 60%, Value: 618
Key: 10%, Value: 104

Running random 10000 times: 0.0202942s
Key: 30%, Value: 3391
Key: 60%, Value: 6635
Key: 10%, Value: 1074

Running random 100000 times: 0.191678s
Key: 30%, Value: 33669
Key: 60%, Value: 66427
Key: 10%, Value: 11004

Running random 1000000 times: 1.77491s
Key: 30%, Value: 334075
Key: 60%, Value: 666087
Key: 10%, Value: 110938

Running random 10000000 times: 18.43691s
Key: 30%, Value: 3332173
Key: 60%, Value: 6667785
Key: 10%, Value: 1111142