Wednesday, May 25, 2016

How did we sort and filter arrays in C# a dozen years ago before generics and LINQ/Lambda magic?

This came up in a conversation over Skype at work today. A coworker was working in some old ASP.NET 1.1 land-before-Cassini horribleness. I'm at home now and looking at my own old notes from back in the day. I wrote the unit test below which, yes, passes. I don't miss this at all. I haven't had to think about this in a long, long time.

using System;
using FluffyNothing.Core.Objects;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FluffyNothing.Tests.Tests.Objects
{
   [TestClass]
   public class PersonTests
   {
      [TestMethod]
      public void Test()
      {
         
//arrange
         Person[] peeps = new Person[]
         {
            new Person(){ Name = "Moe" },
            new Person(){ Name = "Larry" },
            new Person(){ Name = "Curly" },
            new Person(){ Name = "Shemp" }
         };
         
         
//act
         Person[] truncatedPeeps = Array.FindAll(peeps, Filter);
         Array.Sort(truncatedPeeps, Compare);
         
         
//assert
         Assert.AreEqual(truncatedPeeps.Length, 3);
         Assert.AreEqual(truncatedPeeps[0].Name, "Larry");
         Assert.AreEqual(truncatedPeeps[1].Name, "Moe");
         Assert.AreEqual(truncatedPeeps[2].Name, "Shemp");
      }
      
      private bool Filter(Person person)
      {
         if (person.Name != "Curly")
         {
            return true;
         } else {
            return false;
         }
      }
      
      private int Compare(Person yin, Person yang)
      {
         int result = yin.Name.CompareTo(yang.Name);
         return result;
      }
   }
}

No comments:

Post a Comment