0

I have the following code, and need to get a random item that contains the string "Region_1" from the dictionary.

public static Dictionary<int, Tuple<string, int, CurrencyType>> ItemArray = new Dictionary<int, Tuple<string, int, CurrencyType>>()
{
     { 0xB3E, new Tuple<string, int, CurrencyType>("Region_1", 1500, CurrencyType.Fame) }
};

public static int GenerateItemID(string ShopID)
{
     var GeneratedItem = ItemArray.ElementAt(new Random().Next(0, ItemArray.Count)).Key;

}

How do I select this?

DjowYeap
  • 17
  • 1

1 Answers1

3

It's not really possible to this all that efficiently...

First create a static Random at class level... this will prevent non-random behaviour if you run the query frequently over a short period of time... (it's seeded from a discrete clock)

static Random rnd = new Random();

then:

var item = ItemArray.Values
   .Where(t => t.Item1 == ShopID)
   .OrderBy(_ => rnd.Next())
   .FirstOrDefault()
Community
  • 1
  • 1
spender
  • 117,338
  • 33
  • 229
  • 351
  • +1. Note that performance of the method is O(n) due to need to search through all items - unordered dictionary not helping here. – Alexei Levenkov Jun 08 '14 at 01:04