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

Posts Tagged ‘lambda expression’

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

Posted in Lambda Expressions | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 5 – Skip()

Posted by Paul on May 14, 2011

Skip() Extension Method

The Skip() is a simple method that skips the first n elements in the enumerable.

It is similar to Take() method in the sense, Take() will return the first n elements, but Skip() will skip the first n elements. (n is the count of elements)

Parameters: Integer specifying Number of Elements to be skipped

Return Value: List of Items

Example

In the following example we are using a list of integers and the Skip() method to select the top n numbers from the list.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void SkipButton_Click(object sender, EventArgs e)

{

/// Skip method to get a sublist by skipping the first n elements

var result = _list.Skip(3);

foreach (int i in result)

MessageBox.Show(i.ToString());

}

Input

1

2

3

4

5

6

Output

4

5

6

Extension Method Snapshot

You can find the snapshot of the Skip() method usage as provided by Visual Studio.

clip_image002

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 5 – Skip()

Posted by Paul on May 14, 2011

Skip() Extension Method

The Skip() is a simple method that skips the first n elements in the enumerable.

It is similar to Take() method in the sense, Take() will return the first n elements, but Skip() will skip the first n elements. (n is the count of elements)

Parameters: Integer specifying Number of Elements to be skipped

Return Value: List of Items

Example

In the following example we are using a list of integers and the Skip() method to select the top n numbers from the list.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void SkipButton_Click(object sender, EventArgs e)

{

/// Skip method to get a sublist by skipping the first n elements

var result = _list.Skip(3);

foreach (int i in result)

MessageBox.Show(i.ToString());

}

Input

1

2

3

4

5

6

Output

4

5

6

Extension Method Snapshot

You can find the snapshot of the Skip() method usage as provided by Visual Studio.

clip_image002

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 4 – TakeWhile()

Posted by Paul on May 14, 2011

TakeWhile()

The method TakeWhile() is a tricky method. It will take a condition as parameter and it will return the elements until the condition is true and exists the iteration.

It is not similar to Where() condition. Let me take an example. We have 1, 2, 3, 4, 5, 6 in the list and given a condition TakeWhile(i => I != 2) it will return just 1. The method works like below:

It will go through element 1 and as it satisfies the condition it will be yield returned.

On the second element 2 the condition is false and it will exits.

There is no processing for element 3.

Arguments: Condition

Return Value: List of Items

Example

In the following example we are using a list of integers and the Take() method to select the top n numbers from the list.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void TakeWhileButton_Click(object sender, EventArgs e)

{

/// TakeWhile method to get a sublist based on condition

var result = _list.TakeWhile(i => i != 2);

foreach (int i in result)

MessageBox.Show(i.ToString());

}

Extension Method Snapshot

You can find the snapshot of the TakeWhile() method usage as provided by Visual Studio

clip_image002

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 4 – TakeWhile()

Posted by Paul on May 14, 2011

TakeWhile()

The method TakeWhile() is a tricky method. It will take a condition as parameter and it will return the elements until the condition is true and exists the iteration.

It is not similar to Where() condition. Let me take an example. We have 1, 2, 3, 4, 5, 6 in the list and given a condition TakeWhile(i => I != 2) it will return just 1. The method works like below:

It will go through element 1 and as it satisfies the condition it will be yield returned.

On the second element 2 the condition is false and it will exits.

There is no processing for element 3.

Arguments: Condition

Return Value: List of Items

Example

In the following example we are using a list of integers and the Take() method to select the top n numbers from the list.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void TakeWhileButton_Click(object sender, EventArgs e)

{

/// TakeWhile method to get a sublist based on condition

var result = _list.TakeWhile(i => i != 2);

foreach (int i in result)

MessageBox.Show(i.ToString());

}

Extension Method Snapshot

You can find the snapshot of the TakeWhile() method usage as provided by Visual Studio

clip_image002

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 3 – Take()

Posted by Paul on May 14, 2011

The Enumerable.cs class in .Net framework provides n number of useful methods. Let us see each methods one by one.

Take()

The method Take() can be used to get the specified number of top items from the enumerable instance.

Arguments: integer specifying number of items to be selected from the top

Return Value: List of Items

Example

In the following example we are using a list of integers and the Take() method to select the top n numbers from the list.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void TakeButton_Click(object sender, EventArgs e)

{

/// Take method to get a sublist

var result = _list.Take(3);

foreach (int i in result)

MessageBox.Show(i.ToString());

}

Extension Method Snapshot

You can find the snapshot of the Take() method usage as provided by Visual Studio

clip_image002

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 3 – Take()

Posted by Paul on May 14, 2011

The Enumerable.cs class in .Net framework provides n number of useful methods. Let us see each methods one by one.

Take()

The method Take() can be used to get the specified number of top items from the enumerable instance.

Arguments: integer specifying number of items to be selected from the top

Return Value: List of Items

Example

In the following example we are using a list of integers and the Take() method to select the top n numbers from the list.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void TakeButton_Click(object sender, EventArgs e)

{

/// Take method to get a sublist

var result = _list.Take(3);

foreach (int i in result)

MessageBox.Show(i.ToString());

}

Extension Method Snapshot

You can find the snapshot of the Take() method usage as provided by Visual Studio

clip_image002

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 2 – Any()

Posted by Paul on May 14, 2011

The Enumerable.cs class in .Net framework provides n number of useful methods. Let us see each methods one by one.

Any()

The method Any() can be used to test whether any elements in the collection satisfies a particular condition.

Please remember that the previous All() method ensures all the elements satisfy the condition, but the Any() method ensures just any of the elements satisfies the condition.

Return Value: Boolean

Example

In the following example we are using a list of integers and the Any () method is used to validate whether any of the elements are equal to 5.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void AnyButton_Click(object sender, EventArgs e)

{

/// Any method to ensure atleast one elements == 5

var result = _list.Any(i => i == 5);

MessageBox.Show(“Elements == 5: ” + result.ToString());

}

Extension Method Snapshot

You can find the snapshot of the Any() method usage as provided by Visual Studio

clip_image002

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 2 – Any()

Posted by Paul on May 14, 2011

The Enumerable.cs class in .Net framework provides n number of useful methods. Let us see each methods one by one.

Any()

The method Any() can be used to test whether any elements in the collection satisfies a particular condition.

Please remember that the previous All() method ensures all the elements satisfy the condition, but the Any() method ensures just any of the elements satisfies the condition.

Return Value: Boolean

Example

In the following example we are using a list of integers and the Any () method is used to validate whether any of the elements are equal to 5.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void AnyButton_Click(object sender, EventArgs e)

{

/// Any method to ensure atleast one elements == 5

var result = _list.Any(i => i == 5);

MessageBox.Show(“Elements == 5: ” + result.ToString());

}

Extension Method Snapshot

You can find the snapshot of the Any() method usage as provided by Visual Studio

clip_image002

Posted in C# | Tagged: , , | Leave a Comment »

Lambda Expressions Extension Method 1 – All()

Posted by Paul on May 14, 2011

The Enumerable.cs class in .Net framework provides n number of useful methods. Let us see each methods one by one.

All()

The method All() can be used to test whether all elements in the collection satisfies a particular condition.

Return Value: Boolean

Example

In the following example we are using a list of integers and the All() method is used to validate whether all elements are greater than 0.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void AllButton_Click(object sender, EventArgs e)

{

/// All method to ensure all elements are > 0

var result = _list.All(i => i > 0);

MessageBox.Show(“Elements are > 0: ” + result.ToString());

}

Extension Method Snapshot

You can find the snapshot of the All() method usage as provided by Visual Studio

clip_image002

Posted in C# | Tagged: , , | Leave a Comment »