The Code Slinger

September 30, 2008

Randomization & LINQ

Filed under: Uncategorized — Pete @ 3:21 pm
Tags: , ,

Ran into a problem today in which I had a List<T> of items, and I needed to return a number X of them back, but I wanted a random sampling of the original list.  There are plenty of traditional ways to do this, however I figured I’d learn something new and figure out how to do this using LINQ.

Here’s my solution, which I turned into an extension method for future use……

        public static List<T> GetRandom<T>(this List<T> objs, int count)


            var ret = new List<T>();


            if(objs.Count() <= count)

                return objs.ToList();


            var used = new List<int>();

            var seq = (Enumerable.Range(1, count)

                        .Select(a =>


                                var num = (from b in Enumerable.Range(0, objs.Count()-1)

                                           orderby Guid.NewGuid()

                                           where !(from u in used

                                                  select u).Contains(b)

                                           select b).First();


                                return num;



            foreach (int s in seq) { ret.Add(objs[s]); }

            return ret;



Basically the thinking is that since I’m dealing with randomizing what’s in the list, I don’t really care about data specific to the type “T”.  I’m just randomizing the index count from the original list based on how many I want, then using those indexes I get back from the randomization part to pull the actual objects.

The only thing I don’t like about it is the fact that I have to create a separate variable ( “used” ) to keep track of which items in the original list that I’ve already used. Seems there should be a better way to do this within the LINQ query, but at this point I am drawing a blank on that one.

Also…did you notice I am doing randomization without even using the System.Random class? Yeeaaa for me! 😉

As always….Keep on Slangin!


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog at

%d bloggers like this: