LINQ: Tips and Tricks (Part 2)

So, in my previous post LINQ: Tips and Tricks I have demonstrated how to:
- convert a list of objects into a Dictionary
- find how many objects have a certain attribute set to a certain value

Now, I'm back with some tricks that I stumbled upon on Igor Ostrovsky's blog...

Tip 3: How to initialize an array with a single line of code

You can initialize an array to the same value in the following manner:

// Initialize arr to have length of 5 elements
// and each element to have a value -1
int[] arr = System.Linq.Enumerable.Repeat(-1, 5);

There are also some cases when you might need to have an array with values from x to y. You can also accomplish that with a one-liner like this:

// this will initialize arr to have 10 elements
// with values from 0 to 9
int[] arr = System.Linq.Enumerable.Range(0, 10).ToArray();

Tip 4: How to iterate over multiple arrays in a single loop

If you ever find yourself in a situation, where you have to perform a certain task on each element of multiple arrays and you want to avoid having a loop per array, you can use the following trick:

int[] arr1 = Enumerable.Range(0, 10).ToArray();
int[] arr2 = Enumerable.Range(9, 10).ToArray();
 
foreach (int curVal in arr1.Concat(arr2)) {
  Console.WriteLine("Current Value is: {0}", curVal);
}

Tip 5: Generate a random sequence

Suppose you want to iterate over an array of size 5 in random order. Not sure why you would want to do that, but here's how you can do it:

Random rnd = new Random();
var rndSeq = Enumerable.Repeat(0, 5).Select(i => rnd.Next());

Comments