How to randomize sort order in dictionary using Linq

How to randomize sort order in dictionary using Linq

I just came across need where I wanted to shuffle my dictionary with random order.

Here is code snippet which uses Linq to randomize order of key/value pair you added.

using System;
using System.Linq;

namespace MyApp
{
    public class MyClass
    {
        public void DemoRandomSort()
        {
            var dictTest = new Dictionary<int, string>();
            for (int i = 0; i < listCount - 1; i++)
                dictTest.Add(i, "somevalue " + i.ToString());

            Random rand = new Random();
            dictTest = dictTest.OrderBy(x => rand.Next())
              .ToDictionary(item => item.Key, item => item.Value);
        }
    }
}

Binary World is a Software Development company located in Atlanta, USA (since 2007). Binary World specialized in Business Intelligence, mobile, cloud computing and .Net Application Development.

Leave a Reply