Getting Familiar With the Type Related Extenstion Methods – Select(), Cast() and OfType()



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 the 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 a list of integers 1, 2, 3, 4 and 5. We need to convert them into a class containing the 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 a class named ValueIndex:

ExtensionMethods1.gif

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 an exception. But if the classes have an inheritance hierarchy the type casting is possible. We can convert Manager elements to Employee if the former inherits from the latter.

Example: We have an ArrayList of objects of type Car. Eventhough it is of type Car we cannot access it as type Car so we need to do a 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 a car named BMW. The result is shown below:

ExtensionMethods2.gif

Note: You are having an ArrayList of Car objects and you need to call the method Process(IEnumerable<Car> cars) which takes IEnumerable<Car> only.  You can use the Cast() method to achieve the same.

Again, You are having an ArrayList of Car objects and you need to call the method Process(IList<Car> list) which takes IList<Car> only.  You can use the Cast() method and ToList() on it to achieve the same.


Method3: OfType()

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

Example: You have 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 a listbox. We need to select only the Button classes and change their background color. This can be done 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.

ExtensionMethods3.gif

Note

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

Summary

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


Similar Articles