Tag: C#

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:

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?

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?

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.

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.

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.

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:

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.

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:

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 classpublicstaticPropertyInfo[] 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 workpublicstaticIComparable 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;

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.

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;

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.

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:

publicstaticExpression<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) returnExpression.Lambda<Func<T, Boolean>>(
Expression.And(expressionOne.Body, invokedSecond), expressionOne.Parameters
);
}
publicstaticExpression<Func<T, Boolean>> Or<T>(
Expression<Func<T, Boolean>> expressionOne,
Expression<Func<T, Boolean>> expressionTwo
)
{
var invokedSecond = Expression.Invoke(expressionTwo, expressionOne.Parameters.Cast<Expression>());
returnExpression.Lambda<Func<T, Boolean>>(
Expression.Or(expressionOne.Body, invokedSecond), expressionOne.Parameters
);
}

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.