Thursday, July 5, 2012

SelectMany example

This is more magic from C# 4.0 in a Nutshell. This test passes:

using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinqStuff.Tests
{
   [TestClass]
   public class LinqTests
   {
      [TestMethod]
      public void SelectManyTest()
      {
         int[] one = new int[] {1, 77, 8, 35};
         int[] two = new int[] {2, 300};
         int[] three = null;
         int[] four = new int[] {4, 44, 55};
         int[][] five = new int[][] {one, two, three, four};
         List<int> query = five.SelectMany(x => x ?? new int[]{}).ToList();
         Assert.AreEqual(query.Count(), 9);
         Assert.AreEqual(query[0], 1);
         Assert.AreEqual(query[1], 77);
         Assert.AreEqual(query[2], 8);
         Assert.AreEqual(query[3], 35);
         Assert.AreEqual(query[4], 2);
         Assert.AreEqual(query[5], 300);
         Assert.AreEqual(query[6], 4);
         Assert.AreEqual(query[7], 44);
         Assert.AreEqual(query[8], 55);
      }
   }
}

No comments:

Post a Comment