Select N random elements from a List<T> in C#

JC Grubbs picture JC Grubbs · Sep 7, 2008 · Viewed 121.4k times · Source

I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a List<string>.

Answer

Ers picture Ers · Feb 22, 2010

Using linq:

YourList.OrderBy(x => rnd.Next()).Take(5)