Bas Bas - 1 year ago 65
C# Question

Picking random entries from dictionary based on value

I have a dictionary with restaurants and a type of restaurant like this:

Dictionary<Restaurant, string>
Where restaurants is my class and for simplicity I use a string for my type of restaurant.

Let's say I have 25 entries in my list, where there can be groups of 3, 4 or 5 restaurants with the same type. Now I want to narrow this down to select 1 random element per type.

I have found this page which explains how to pick random values from a dictionary, but how would I go around picking a random entry per grouping of type?

Let me know if I should elaborate more or if you need additional information!

Edit: example of my code:

Dictionary<Restaurant, string> restaurants = new Dictionary<Restaurant, string>();

randomRestaurants.Add(restaurants.GroupBy(x => x.string).//Randomly pick an entry per grouping and add it to list//

List<Restaurant> randomRestaurants = new List<Restaurant>();

For example: Possible types can be
Fast food

I would like to apologize for asking another confusing question. I'll pay more attention before I post something.

Answer Source

First idea (for any usage of this list) would be to order your data source into a more sensible format, that is, a key value structure wherein the key type is the thing that identifies a subset of restaurants (string), and the value is a list of the Restaurants within it.

You can do this using code similar to the following:

var sensibleDict = sillyDict
    .GroupBy(kv => kv.Value)
        m => m.Key,
        m => m.Select(kv => kv.Key).ToList());

Now, we can simply randomise the result and take the first after randomisation to convert that into a Key => Single Value item.

var randomDict = sillyDict
    .GroupBy(kv => kv.Value)
        m => m.Key,
        m => m.Select(kv => kv.Key)
            .OrderBy(k => Guid.NewGuid())

This will get you a Dictionary<string, Restaurant> wherein the first string is the type of food (ie. Italian, Sushi) and the second is the random Restaurant.

Note: As I said in my comment, this isn't the most efficient way to order a list if your dataset gets large. For better methods of shuffling a list, take a look at this answer - Randomise a List.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download