Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

    Advertisements
  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

Getting Familiar with the Type releated Extenstion Methods – Select(), Cast(), OfType()

Posted by Paul on May 14, 2011


The class Enumerables.cs provides various extension methods for the built-in classes like IList, ArrayList, IEnumerable etc. Among these the above 3 methods are dealing with type of the underlying element. Let us see what each can be the purpose of.

Method1: Select()

This method is used to convert one type to another. Please note that we are manually creating the instance of the new type here.

Example: We have got a list of integers 1, 2, 3, 4 and 5. We need to convert them into a class containing properties Value and Index.

private void SelectButton_Click(object sender, EventArgs e)

{

// List is holding int values

IList<int> list = new List<int>();

list.Add(1);

list.Add(2);

list.Add(3);

list.Add(4);

list.Add(5);

// Convert them to class ValueIndex

var result = list.Select((v, i) => new ValueIndex() { Value = v, Index = i });

// Display

lbx.Items.Clear();

foreach (ValueIndex vi in result)

lbx.Items.Add(vi.ToString());

}

On execution we can see that the int values got converted into class named ValueIndex:

clip_image002

Method2: Cast()

This is a tricky method. It is used to convert a type in a non-generic list to a typed IEnumerable. We can use this to convert the T objects in an ArrayList to typed IEnumerable<T>.

Note: The method throws InvalidCastException if the casting cannot be supported. An int to long casting will throw exception. But if the classes have an inheritance hierarchy the type casting is possible. We can convert a Manager elements to Employee if the former inherits from the latter.

Example: We have got an ArrayList of object s of type Car. Eventhough it is of type Car we cannot access it as type Car and we need to do conversion. The following code operates on the non-generic ArrayList and returns an IEnumerable<Car>.

private void CastButton_Click(object sender, EventArgs e)

{

// Non-generic list

ArrayList arrayList = new ArrayList();

arrayList.Add(new Car() { Name = “BMW” });

arrayList.Add(new Car() { Name = “Jaguar” });

arrayList.Add(new Car() { Name = “Nissan” });

// Convert the non-generic list into a generic IEnumerable

IEnumerable<Car> result = arrayList.Cast<Car>();

// Now we can work on the properties

IEnumerable<Car> bmwResult = result.Where(c => c.Name == “BMW”);

// Display

lbx.Items.Clear();

foreach (Car car in bmwResult)

lbx.Items.Add(car);

}

On execution, the above code converts the non-generic list items into IEnumerable<Car> and uses the Where() method to filter by car named BMW. The result is shown below:

clip_image004

Method3: OfType()

This method can be used to filter the result based on specific type.

Example: You have got a list of unrelated objects. In this example we are taking the current demo form as the container of different UI Elements. The form.Controls property contains buttons and listbox. We need to select only the Button classes and change the back color. This can be accomplished using the OfType() method.

private void OfTypeButton_Click(object sender, EventArgs e)

{

// Get the Button controls only

var buttonList = this.Controls.OfType<Button>();

// Change BackColor

foreach (Button button in buttonList)

button.BackColor = Color.YellowGreen;

}

On execution we can see that the current buttons on the form are selected and the backcolor is changed.

clip_image006

Note

The above mentioned methods are residing in the class Enumerables of .Net framework. The methods are available to the IList, ArrayList classes through the extension methods mechanism.

Summary

In this article I have tried to portray the usage of 3 Extension Methods. Using Select() extension method we can convert types, using Cast() we can work on a non-generic list to get an IEnumerable, using OfType() we can access the objects of particular type.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s