The Switch Remover: Convert Switch Statements to Dictionaries

Folks, what if I told you that Switch is a thing of the past? What if I told you I had a way to reduce code in certain areas so that you don’t have that messy Switch logic? What would you pay for that? Would you pay $19.95? Not convinced? Well take this:

  switch(someDropDownList.SelectedValue)
  {
     case "hi":
        CallThisMethod();
        CallThatMethod();
        CallAnotherMethod();
        break;
     case "there":
        CallThisMethod();
        CallThatMethod();
        CallAnotherMethod();
        CallSomethingElse();
        break;
  }

And I’ll give you this:

  doSomething[someDropDownList.SelectedValue]();

I bet you’re ready to pay $19.95, but wait there’s more. I’ll actually throw in how I did such an amazing thing.

  Dictionary<String, Action> switchRemover = new Dictionary<String, Action>();
  switchRemover.Add("hi", () => RunHiMethod();
  switchRemover.Add("there", () => RunThereMethod();

Why that’s amazing! But wait, I must be pulling something. What are these RunHiMethod and RunThereMethod methods? I must be pulling a fast one. Well, all they are is what the switch was doing before all wrapped up into one method. Don’t get it?

  private void RunHiMethod()
  {
      CallThisMethod();
      CallThatMethod();
      CallAnotherMethod();
  }

But… but what if I had to pass something in? What would I do then??? Boy you got me there, I could tell you but I’d have to charge you more. Wait… I’ll even throw that in for free. That’s right. Remember that old mess we had?

  switch(someDropDownList.SelectedValue)
  {
     case "hi":
        CallThisMethod(someUser);
        CallThatMethod();
        CallAnotherMethod();
        break;
     case "there":
        CallThisMethod(someUser);
        CallThatMethod();
        CallAnotherMethod();
        CallSomethingElse();
        break;
}

Well shoot,we could do something like this:

  Dictionary<String, Action<User>> switchRemover = new Dictionary<String, Action>();
  switchRemover.Add("hi", currentUser => RunHiMethod(currentUser);
  switchRemover.Add("there", currentUser => RunThereMethod(currentUser );

And then:

  doSomething[someDropDownList.SelectedValue](currentUser);

That’s amazing! You ready with your credit card? I knew you would be.

The Switch Remover does not come with a warranty.
The Switch Remover can not be used in all circumstances.
The Switch Remover assumes no fault for any physical conditions caused by the sudden surge of awesomeness you might feel.

SO BUY IT NOW!

Uhg It Won’t End

Still on the readability thing, but there was a second argument in the post that inspired now what is three posts of my own here. The question was should you use Linq based on people saying it’s more readable, therefore just making it syntax sugar.

  foreach(Item current in itemList)
  {
     itemNameList.Add(current.Name);
  }

Versus

 var itemNameList = from item in itemList
                    select item.Name;

Or

  Func<Item, String> itemName = current => current.Name;
  itemNameList.Select(itemName);

So at this point it’s really a matter of preference. Problem is, you have to look closer to why the third is so much more than syntax yummies.

Say you want a method that takes in a UserList and you want to select all the users that have a property (Could be name, address, whatever) that matches a string. Well you could do this:

 public IList<User> AllUsersThatMatch(IList<User> userList, NeededProperty property, String value)
 {
    IList<User> returnList;

    returnList = new List();

    foreach(UserItem currentUser in userList)
    {
        switch(property)
        {
            case(NeededProperty.Name):
                if(currentUser.Name == value)
                {
                    userList.Add(currentUser);
                }
                break;
            case(NeededProperty.Phone):
                if(currentUser.Phone == value)
                {
                    userList.Add(currentUser);
                }
                break;
        }
    }
 }

Or you could do this:

 public Func<User, Boolean> MatchesProperty(NeededProperty property, String value)
 {
    Func<User, Boolean> returnValue;

    switch(property)
    {
        case NeededProperty.Name:
            returnValue = currentItem => currentItem.Name == value;
            break;
        case NeededProperty.Phone:
            returnValue = currentItem => currentItem.Phone == value;
            break;
    }
    return returnValue;
  }

 public IList<User> AllUsersThatMatch(IList<User> userList, NeededProperty property, String value)
 {
    IList<User>  returnList;

    returnList = userList.Where(MatchesProperty(property, value));
    return returnList;
 }

Now which do you think is easier to upkeep? For those of you wondering what I did, I simply used a method that would return the Func I needed for the passed in Enum and called it in the Where clause. The amount of code is probably close to the same right now, but add in 5 more values for the NeededProperty enum and you’ll see the code amount differing more and more.

I realize this isn’t the best of example, and probably the first way could be refactored but the idea is still there. The Linq Method approach gives you a lot more flexibility in the long run with dynamic stuff like this.

What Is Readable Addon

Quick thought too about which to use due to readability:

var you = from factor in seansAwesomeness
          select new FactorLite
          {
             Amount = amount;
          };

or you could do:

Func<Person, FactorLite> selectFactorLite = currentFactor => new FactorLite { Amount = currentFactor.Amount };

seansAwesomeness.Select(selectFactorLite);

I guess it’s a matter of preference, but the first seems way too verbose for something too simple.

What Is Readable

So a couple of posts I read recently have been about readability of Linq, more so Linq query expressions versus the Linq methods. Don’t know what I mean?

Expression:

var result = from knowledge in Sean
             select knowledge.Linq;

As opposed to:

var result = Sean.Select(knowledge => knowledge.Linq);

Personally I would replace the lambda expression with a Func, but I can live with it right now. Anywho, the argument is that the first looks better than the second. I really don’t see this as a looks problem, but a useage problem. Fact is, they both have their uses and you should know how to read both. Why is that? Well here’s an example CAUSE I KNOW YOU WANT ONE!

One of my earlier posts had to do with solving the FizzBuzz thing with Linq where I gave you this bad ass solution:

 var result =
      listToConvert
      .Where(WhereBothDivisible(fizzNumber, buzzNumber))
      .Select(selectKeyValuePair("FizzBuzz"))
      .Concat(
            listToConvert
            .Where(WhereBuzzDivisable(fizzNumber, buzzNumber))
            .Select(selectKeyValuePair("Buzz")))
            .Concat(
                  listToConvert
                  .Where(WhereFizzDivisable(fizzNumber, buzzNumber))
                  .Select(selectKeyValuePair("Fizz")))
                  .Concat(
                         listToConvert
                        .Where(WhereNeitherDivisable(fizzNumber, buzzNumber))
                        .Select(selectKeyValuePair("Nothing")));

As you can see, I’ve used both Func fields and methods to return Funcs to clean up how this would look. I’ll even show what it would look like without this approach:

var result = listToConvert.Where(currentItem =>
             IsDivisible(currentItem, fizzNumber) && IsDivisible(currentItem, buzzNumber)
             ).Select(currentItem => new KeyValuePair(currentItem, "FizzBuzz")).Concat(...

Now I can totally admit that this second one I am showing is just ouch. So the first lesson to be learn is that Funcs and Methods that return Funcs can significantly clean up the Linq Method approach.

Now you could do the same with expressions:

 var fizzBuzz = from currentNumber in listToConvert
                where WhereBuzzDivisable(fizzNumber, buzzNumber)
                select selectKeyValuePair("FizzBuzz");

 var buzz = from currentNumber in listToConvert
            where WhereBuzzDivisable(fizzNumber, buzzNumber)
            select selectKeyValuePair("Buzz");

 var fizz = from currentNumber in listToConvert
            where WhereFizzDivisable(fizzNumber, buzzNumber)
            select selectKeyValuePair("Fizz");

var neither = from currentNumber in listToConvert
              where WhereNeitherDivisable(fizzNumber, buzzNumber)
              select selectKeyValuePair("Fizz");

Ok so nice and pretty, but now what? Concatenation. This is where is gets ugly:

  fizzBuzz.Concat(fizz.Concat(buzz.Concat(neither))));

OR

 var fizzBuzz = from currentNumber in listToConvert
                where WhereBuzzDivisable(fizzNumber, buzzNumber)
                select selectKeyValuePair("FizzBuzz")
                .Concat(
                     from currentNumber in listToConvert
                     where WhereBuzzDivisable(fizzNumber, buzzNumber)
                     select selectKeyValuePair("Buzz"))
                     .Concat(....);

See what I’m getting at? The non expression one is looking a bit better now or maybe this is a fight to see which is less fugly. Now I admit that this may not be the best FizzBuzz solution, but it gives an example or where the Linq queries can go very wrong.

Dynamic Linq: OrderBy Using a String for a Property Name

Now this is kind of dangerous to do since there is no compile time check (Like most things set in markup) but say you want to sort a collection, using the Linq extension methods, but you don’t know what you what to sort on at any given time. On top of that, you have a datagrid and a bunch of sort expressions to deal with. Now you could do something like create a hashtable full of lambda expressions that the key is the sort expression:

Dictionary<String, Func<User, IComparable>> list;

userList = User.GetUserList();
list = new Dictionary<String, Func<User, IComparable>>();
list.Add("UserName", currentUser => currentUser.UserName);
list.Add("UserID", currentUser => currentUser.UserID);
userList.OrderBy(list["UserID"]);

Works just fine, and might be preferable to what I’m about to show. OooOoOO sound eerie?

//This is just to get the property info using reflection.  In order to get the value
//from a property dynamically, we need the property info from the class
public static PropertyInfo[] GetInfo<K>(K item) where K : class
{
  PropertyInfo[] propertyList;
  Type typeInfo;

  typeInfo = item.GetType();
  propertyList = typeInfo.GetProperties();

  return propertyList;
}

//This is the dynamic order by func that the OrderBy method needs to work
public static IComparable OrderByProperty<T>(String propertyName, T item)
  where T : class
{
  PropertyInfo[] propertyList;

  propertyList = GetInfo(item);

  //Here we get the value of that property of the passed in item and make sure
  //to type the object (Which is what GetValue returns) into an IComparable
  return (IComparable)propertyList.First(currentProperty
    => currentProperty.Name == propertyName).GetValue(item, null);
}

And use:

//This takes the current user and calls the OrderByProperty method which in turn
//gives us the Func OrderBy is requesting.
var test = userList.OrderBy(currentUser
  => DynamicPropertySort.OrderByProperty("UserID", currentUser)).ToList();

Ok so what the hell? I mean intellisense on the OrderBy method doesn’t give much help. Func<<User, TKey>>. Yeah ok. So basically the return type is open. Well this kind of sucks right? Because I would have to return a Func that already knows the return type. (Be it string, int, ect) Of course, this would mean we would have to handle each sort expression in code. NOT VERY DYNAMIC IS IT? Well f that. Truth is, what the order by is looking for is a Func that takes in a User and returns something it can compare. This is where IComparable comes in.

The OrderBy has to take the returned value, say UserID which is an int, and figure out how to compare it to another value. Pretty simple. So as long as the property you are ordering by uses IComparable, you’re good to go. Pretty nice huh?

Now I would suggest, if you use this (HAHAHAHA), is to cache a dictionary of the property info with the class type as the key so that you don’t have to use as much reflection everytime. I just didn’t put that in.

U U USING

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

More Fun With Linq

Say you have a class named BannedProgram and it has a collection of DayOfWeek and a string ProcessName. Now the collection of DayOfWeek is basically a way to set the days of the week it’s banned. With this you want to create a collection of these BannedPrograms, each with their own names and days they are banned. Simple, I know.

Next you have a list of processes that are currently running and you want to get all the processes that match the names in the BannedPrograms list AND if the current day is a banned day.

First you need the day checked function:

private static Func<DayOfWeek, Boolean> dayIsToday =
  currentDay => currentDay == DateTime.Now.DayOfWeek;

Then you need the method to get the banned processes that are currently running:

private static Process[] GetBannedProcesses(BannedProgram[] programs, Process[] processes)
{
  var processList = from process in processes
  where
  (
    from program in programs
    where program.DaysBanned.Any(dayIsToday)
    select program.ProcessName
  ).Contains(process.ProcessName)
  select process;

  return processList.ToArray();
}

What this is doing:

Well if you look at this:

from program in programs
where program.DaysBanned.Any(dayIsToday)
select program.ProcessName

This is going to grab any BannedProgram that has a DayOfWeek that matches today and it will select only it’s name. This will give you a list of names of the BannedProcesses that can not be played today.

var processList = from process in processes
where
(
  from program in programs
  where program.DaysBanned.Any(dayIsToday)
  select program.ProcessName
).Contains(process.ProcessName)

This checks to see if any of the currently running processes have a name that matches a name in the banned program list.

And now you have a list of processes to kill. Yay. Not sure this is a big deal, just thought it was a fun example of using linq and subselects.

USING???

using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Windows.Forms;

More Useless info

Just in case you wanted to create something to kill a process, I have this little bit:

using System;
using System.Diagnostics;

Action<Process> killProcess = currentProcess => currentProcess.Kill();
Process[] processes;
String processToKill;

processToKill = "WAR";
processes = Process.GetProcesses();

processes.Select(currentProcess => currentProcess.ProcessName == processToKill)
.ToList()
.ForEach(killProcess);

I originally intended this as a service that would kill processes that were running on a specific day. IE To stop myself from playing games during the week. Problem was finding a way to stop me from killing the service. Now you can set a service to disallowing stopping it. The idea being that I would have another program that would stop it only if a password was enter correctly. (A certain woman would have this password) Trouble is, I can just open up the task manager and kill the process. Now I have to rely on self control. WHICH IS THE REASON WHY I WANTED THIS IN THE FIRST PLACE.

Combine Lambda Expressions: The And and the Or

Found this post here but wanted to make a really simple example to demonstrate this.

The idea is simple, take something like this:

currentItem => currentItem.BooleanMethodOne() && currentItem.BooleanMethodTwo()

but say you only want to have one clause or both. Well you could make three separate expressions, but what if you wanted to add even more later? What if you wanted to mix and match? What if you’re reading thing because you watched to see what page could possibly be on the last page of a google search? Well I have answers… stolen answers.

First the needed And and Or methods:

public static Expression<Func<T, Boolean>> And<T>(
   Expression<Func<T, Boolean>> expressionOne,
    Expression<Func<T, Boolean>> expressionTwo
)
{
  //Basically this is like a bridge between the two expressions.  It will take the T
  //parameter from expressionOne and apply it to expression two. So if 
  // oneItem => oneItem.OneMethod() is expressionOne
  // twoItem => twoItem.TwoMethod() is expressionTwo
  //it would be like replacing the twoItem with the oneItem so that they now point
  //to the same thing.
  var invokedSecond = Expression.Invoke(expressionTwo, expressionOne.Parameters.Cast<Expression>());

  //Now this is to create the needed expresions to return.  It will take both early expressions
  //and use the item from the first expression in both.
                    
  //It will look something like this:
  //currentItem => (currentItem.OneMethod And Invoke(currentItem => currentItem.TwoMethod()))
  //As you can see, it looks to be running expressionOne and then a new method that basically
  //calls expressionTwo with the same value (currentItem)
  return Expression.Lambda<Func<T, Boolean>>(
   Expression.And(expressionOne.Body, invokedSecond), expressionOne.Parameters
  );
}

public static Expression<Func<T, Boolean>> Or<T>(
Expression<Func<T, Boolean>> expressionOne, 
Expression<Func<T, Boolean>> expressionTwo
)
{
  var invokedSecond = Expression.Invoke(expressionTwo, expressionOne.Parameters.Cast<Expression>());

  return Expression.Lambda<Func<T, Boolean>>(
   Expression.Or(expressionOne.Body, invokedSecond), expressionOne.Parameters
  );
}

And here’s a test for it:

String[] list;

list = new String[] { "a", "b", "c", "ac", "ab", "cc", "d", "dd", "dc" };

Expression<Func<String, Boolean>> stringLikeA = currentString => currentString.Contains("a");
Expression<Func<String, Boolean>> stringLikeB = currentString => currentString.Contains("b");
Expression<Func<String, Boolean>> stringLikeC = currentString => currentString.Contains("c");

Expression<Func<String, Boolean>> neededUser = And<String>(stringLikeA, stringLikeB);
list.Where(neededUser.Compile());

//a
Assert.IsTrue(list.Where(neededUser.Compile()).Count() == 1);  //ab

//a, c, ac, ab, cc, dc
neededUser = Or<String>(stringLikeA, stringLikeC);

Assert.IsTrue(list.Where(neededUser.Compile()).Count() == 6);

//ab, c, ac, cc, dc
neededUser = And<String>(stringLikeA, stringLikeB);
neededUser = Or<String>(neededUser, stringLikeC);
Assert.IsTrue(list.Where(neededUser.Compile()).Count() == 5);

USINGS!!ONEONE

using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

Solve FizzBuzz Using Linq Extension Methods

So if you haven’t heard of the FizzBuzz test, it’s basically taking in a list of numbers and figuring out if they are divisible, cleanly, by two numbers. Say you have 3 and 5 and this is your list:

1

3

5

10

15

If the number is divisible by 3, then return the Fizz string. If the number is divisible by 5, return a Buzz string. If it’s divisible by both, then return FizzBuzz.

1

Fizz

Buzz

Buzz

FizzBuzz

Pretty simple and in actuality pretty easy to do with old C# tools, but I wanted to do this with Linq. With the use of Funcs, Actions, and Linq extension methods it can be done fairly easily. Technically you can do the whole thing in one line if you don’t want to bother with refactoring.

I have no idea how to format this cleanly, so sorry if the format is confusing. Basically it is take a list, get the ones you want, concatenate it with the next list.

public static IList<KeyValuePair<Int32, String>> ConvertListOfIntegersWithLinqMethods(IList<Int32> listToConvert, Int32 fizzNumber, Int32 buzzNumber)
{
var result =
  listToConvert
    .Where(WhereBothDivisible(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair("FizzBuzz"))
    .Concat(
  listToConvert
    .Where(WhereBuzzDivisable(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair("Buzz")))
    .Concat(
  listToConvert
    .Where(WhereFizzDivisable(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair("Fizz")))
    .Concat(
  listToConvert
    .Where(WhereNeitherDivisable(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair("Nothing")));

 return result.ToList().OrderBy(currentItem => currentItem.Key).ToList();
}

Using these:

private static Func<Int32, KeyValuePair<Int32, String>> selectKeyValuePair(String value)
{
 return currentItem => new KeyValuePair<Int32, String>(currentItem, value);
}

private static Func<Int32, Boolean> WhereBothDivisible(Int32 fizzNumber, Int32 buzzNumber)
{
 return  currentItem => IsDivisible(currentItem, fizzNumber) && IsDivisible(currentItem, buzzNumber);
}

private static Func<Int32, Boolean> WhereFizzDivisable(Int32 fizzNumber, Int32 buzzNumber)
{
 return currentItem => IsDivisible(currentItem, fizzNumber) && !IsDivisible(currentItem, buzzNumber);
}

private static Func<Int32, Boolean> WhereBuzzDivisable(Int32 fizzNumber, Int32 buzzNumber)
{
 return currentItem => !IsDivisible(currentItem, fizzNumber) && IsDivisible(currentItem, buzzNumber);
}

 private static Func<Int32, Boolean> WhereNeitherDivisable(Int32 fizzNumber, Int32 buzzNumber)
{
 return currentItem => !IsDivisible(currentItem, fizzNumber) && !IsDivisible(currentItem, buzzNumber);
}

Beyond the wall

So I never gave a solution to this problem and thought I might do that real fast.

If you recall, this was the main sticking point of creating a Func for a select clause:

Func<User, EHH??> selectUserID = currentUser =>  new { currentUser.ID, currentUser.UserName };

Well there is no one solution to this, but there is an easy and clean solution:

 public class UserQueryItem
 {
   public UserQueryItem ( Int32 userID, String userName )
   {
      UserID = userID;
      UserName = userName;
   }

   public Int32 UserID { get; set; }
   public String UserName { get; set; }
 }

Create a class to hold the information.

 Func<User, UserQueryItem> selectUserID = currentUser =>  new UserQueryItem { UserID = currentUser.ID, UserName = currentUser.UserName };

Or

 Func<User, UserQueryItem> selectUserID = currentUser =>  new UserQueryItem (currentUser.ID, currentUser.UserName);

Pretty simple, just a little more work.