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); } } }
Leave a Reply
You must be logged in to post a comment.