Enumerating Through a String

I discovered something cool about strings the other day, and I must admit it is incredibly obviously and I do feel a rather stupid for not knowing this. I’ve never seen any code using this technique to enumerate through the characters in a string, maybe you have?

So normally developers would usually do something like this to enumerate through the characters in a string:


char[] charArray = "Hello World".ToCharArray();
foreach (char ch in charArray)
{
    // Do something (with ch)
}

Or maybe:


string value = "Hello World";
for (int index = 0; index < value.Length; index++)
{
    char ch = value[index];
    // Do something (with ch)
}

Or some other technique.

So I wanted to see if string implemented IFormattable, don’t ask why, it was a random thought going through my head and I discovered string implements a number of interesting interfaces, namely:

  • IComparable
  • ICloneable
  • IConvertible
  • IComparable
  • IEnumerable
  • IEnumerable
  • IEquatable

The most interesting being IEnumerable because it allows you to do the following:


foreach (char ch in "Hello World")
{
    // Do something (with ch)
}

And you can do LINQ queries directly against the characters in a string:


var ordinalValues = from ch in "Hello World"
                    select (int)ch;

Which I think is pretty cool :)

Adding a custom insert stored procedure to a LINQ entity

Normally when you commit a change to the database using LINQ it will generate SQL to perform the insert/update/delete action. Most of the time this is fine, but LINQ does provide the ability to override this behaviour and specify a stored procedure that should be executed instead of the default behaviour. And luckily it’s really easy.

First, create your stored procedure, normally if you are creating an insert or update stored procedure the proc will have a parameter for each field but this is not a requirement as you can map the individual fields to the properties of the class.

Drag the stored procedure onto your DBML so that the LINQ framework creates a method for the stored procedure, in this example the stored procedure is called InsertLessee.

LINQInsert1

Then right click on the LINQ entity in the DBML and select Configure Behaviour.

LINQInsert2

Then (1) choose the behaviour to replace, (2) select Customize and select the stored procedure from the drop down list, in this case InsertLessee, and (3) if needed alter the stored procedure parameter to class property mapping.

LINQInsert3

It is as simple as that, now whenever a Lessee is inserted the LINQ framework will call the stored procedure instead of generating SQL at runtime.

New features in .Net 3.5 – Anonymous Types and Implicitly Typed Local Variables

Anonymous Types and Implicitly Typed Local Variables are two new features to the .Net 3.5 framework that work hand in hand and are used mainly with LINQ.

Anonymous Typing allows you to create a class without explictly defining the class, for example say you needed a class that contained the properties FirstName and LastName but you were only going to use it inside a single method and you didn’t want to define a class just for a one off usage.

Using anonymous typing you could create the class as follows:

var person = new {FirstName = "John", LastName = "Smit"}

Implicitly Typed Local Variable allows variables to be declared without having to specify the type at design-time. The strong-type assigned to the variable is inferred at compile-time from the initialization expression. This gives you some of the benefits of a dynamic type with the advantages of compile time checking.

So if the following Implicitly Typed Local Variables were declared:
(The var keyword denotes an Implicitly Typed Local Variable)

var person = new {FirstName = "John", LastName = "Smit"}
var num = 5;
var str = “Example”;

The compiler will know that the variable person is an object with the properties FirstName and LastName, and that num is an integer and str is a string. Basically whatever is on the right hand side of the equal sign defines the type of the variable. Once the variable has been declared it is type safe, so you won’t be able to assign the incorrect type to it or call members on it that don’t exist, in those cases a compile time error will occur.

The major use for Anonymous Types and Implicitly Typed Local Variables is with LINQ, when performing a LINQ query you may want to return information from multiple objects into a single object, now instead of having to create a class defining the properties you want to return from the query you can use Anonymous Types and Implicitly Typed Local Variables.

For example:

var cities = from city in Cities
             join state in States on city.State equals state
             select new
             {
                 CityName = city.Name,
                 StateName = state.Name
             };

In this example I only want to retrieve the city name and state name, but the properties I want are on two objects so I create a new anonymous type which is assigned to an implicitly typed local variable.

There are a couple of important restrictions when using the var keyword:

  • The declaration must have an initializer that the compiler can resolve to a type definition.
  • The initializer expression cannot evaluate to null. The compiler must be able to determine the type.
  • A type called var cannot be in the same scope, otherwise it is used.
  • The var keyword must only be used for local variable declaration.

Disclaimer: This post is based on Orcas CTP June 2007