Monday, March 2, 2015

examples of .Take and .TakeWhile in C#

Take is going to pull the first x number of items from a collection into a new collection. TakeWhile will start crawling forward in the collection looking for matches. Both of these tests pass:

using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Whatever.Tests
{
   [TestClass]
   public class UnitTests
   {
      [TestMethod]
      public void TakeTest()
      {
         string[] array = new string[] { "foo", "bar", "baz", "qux" };
         string concatenation = "";
         var taken = array.Take(2);
         foreach (string piece in taken) concatenation = concatenation + piece;
         Assert.AreEqual(concatenation, "foobar");
      }
      
      [TestMethod]
      public void TakeWhileTest()
      {
         string[] array = new string[] { "foo", "bar", "baz", "qux" };
         string concatenation = "";
         var taken = array.TakeWhile(item => item.Length < 4);
         foreach (string piece in taken) concatenation = concatenation + piece;
         Assert.AreEqual(concatenation, "foobarbazqux");
      }
   }
}

No comments:

Post a Comment