One of the many joys I get from programming is creating beautiful LINQ expressions in C#. This is one I made today to create a random sequence of integers containing a few doubles. The Shuffle method is an extension I wrote a while back. It basically creates a random order of an Enumerable.
itemsInOrder = Enumerable.Range(0, itemCount)
.Concat(
Enumerable.Repeat(
Enumerable.Range(0, itemCount), doubleOccurance)
.Aggregate(Enumerable.Concat)
.Shuffle()
.Take(numDoubles))
.Shuffle()
.ToArray();
Gotta love those things.



Comment by Yorick on December 14, 2011 at 11:14 am
Yeahh LINQ is fun
.
Does the shuffle method also do lazy evaluation? So ArrayWithAMillionItems.Shuffle().Take(5) would not shuffle a million items?
Comment by Bas on December 14, 2011 at 11:35 am
Unfortunately it doesn’t.. I couldn’t find a descend algorithm to do that. Do you know of any?
Comment by Yorick on December 19, 2011 at 10:19 pm
Heh just realized it doesn’t really matter. You have to iterate over the whole input anyway because you need to count them and take a random item which could well be the millionth. You can’t handle the input as if it’s endless, like you can with a Take or Map/Select. I don’t think the shuffling part will make much of a difference after that.