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

Archive for the ‘Lambda Expressions’ Category

Grouping using Lambda Expressions

Posted by Paul on November 4, 2011

// Group the list based on Serial Number

// Result should be SerialNumber, Month, SUM(Value)

/// Good Challenge?

private void DoGrouping()
{
    IList<Item> list = new List<Item>();
    list.Add(new Item() { SerialNumber = 1, Month = “Jan-2010”, Value = 2 });
    list.Add(new Item() { SerialNumber = 1, Month = “Jan-2010”, Value = 5 });
    list.Add(new Item() { SerialNumber = 2, Month = “Feb-2010”, Value = 1 });
    list.Add(new Item() { SerialNumber = 2, Month = “Feb-2010”, Value = 6 });
    list.Add(new Item() { SerialNumber = 2, Month = “Feb-2010”, Value = 2 });
    list.Add(new Item() { SerialNumber = 3, Month = “Mar-2010”, Value = 7 });
    list.Add(new Item() { SerialNumber = 3, Month = “Mar-2010”, Value = 4 });

    IList<Item> groupedList = list.GroupBy(i => i.SerialNumber).Select(g => new Item() { SerialNumber = g.Key, Month = g.First().Month, Value = g.Sum(gr => gr.Value) }).ToList<Item>();
}

public class Item
{
    public int SerialNumber;
    public string Month;
    public int Value;
}

Advertisements

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

Lambda Expressions Extension Methods Series 12 – ToLookup()

Posted by Paul on May 26, 2011

The extension methods inside Enumerable.cs includes ToLookup() probably the most unused one. The purpose of the method is to create a lookup list based on key values.

Operates on: IEnumerable

Returns: ILookup<T1, T2>

Please note that the return value is a an interface of ILookup which contains 2 generic arguments. The first generic argument performs as the key and the values will be an IEnumerable of the original type.

Example

The sample list contains strings of various lengths.

private void ToLookupButton_Click(object sender, EventArgs e)

{

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

list.Add(“as”);

list.Add(“is”);

list.Add(“has”);

list.Add(“can”);

list.Add(“this”);

list.Add(“that”);

// Now there are 6 items in the list with length of 2, 3 and 4

ILookup<int, string> lookupList = list.ToLookup(s => s.Length);

// Get the lookup values for length 2

foreach (string value in lookupList[2])

MessageBox.Show(“Lookup Values for Length 2: ” + value);

}

The output of the application would be:

Lookup Values with length 2 are: as, is

Code Explained

From the above code we can see that a list was created with six string items. Then the ToLookup() method is called by passing the length as parameter. The method will return a key value pair where key equals the length and the value an IEnumerable which contains the items corresponding to the key.

Key

Values

2

as

 

is

3

has

can

4

this

 

that

Advanced Example

Now let us take a more real time example where we have a series of Employee objects having Id, Age and Name as the properties. We need to create a lookup list based on their age. The result will be having Age as key and the corresponding Employee objects.

private void ToLookupAdvanced_Click(object sender, EventArgs e)

{

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

list.Add(new Employee() { Id = 1, Age = 20, Name = “Kavin” });

list.Add(new Employee() { Id = 2, Age = 30, Name = “Alen” });

list.Add(new Employee() { Id = 3, Age = 20, Name = “Suresh” });

list.Add(new Employee() { Id = 4, Age = 30, Name = “Jay” });

list.Add(new Employee() { Id = 5, Age = 20, Name = “Nanda” });

ILookup<int, Employee> lookupList = list.ToLookup(employee => employee.Age);

foreach (Employee employee in lookupList[20])

MessageBox.Show(employee.ToString());

}

The result of the above code will be Employee objects with Age = 20:

1 Kavin

3 Suresh

5 Nanda

The class structure of Employee would be:

public class Employee

{

public int Id;

public double Salary;

public int Age;

public string Name;

public override string ToString()

{

return this.Id.ToString() + ” ” + this.Name;

}

}

Extension Method Snapshot

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

clip_image002

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

Lambda Expressions Extension Methods Series 12 – ToLookup()

Posted by Paul on May 26, 2011

The extension methods inside Enumerable.cs includes ToLookup() probably the most unused one. The purpose of the method is to create a lookup list based on key values.

Operates on: IEnumerable

Returns: ILookup<T1, T2>

Please note that the return value is a an interface of ILookup which contains 2 generic arguments. The first generic argument performs as the key and the values will be an IEnumerable of the original type.

Example

The sample list contains strings of various lengths.

private void ToLookupButton_Click(object sender, EventArgs e)

{

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

list.Add(“as”);

list.Add(“is”);

list.Add(“has”);

list.Add(“can”);

list.Add(“this”);

list.Add(“that”);

// Now there are 6 items in the list with length of 2, 3 and 4

ILookup<int, string> lookupList = list.ToLookup(s => s.Length);

// Get the lookup values for length 2

foreach (string value in lookupList[2])

MessageBox.Show(“Lookup Values for Length 2: ” + value);

}

The output of the application would be:

Lookup Values with length 2 are: as, is

Code Explained

From the above code we can see that a list was created with six string items. Then the ToLookup() method is called by passing the length as parameter. The method will return a key value pair where key equals the length and the value an IEnumerable which contains the items corresponding to the key.

Key

Values

2

as

 

is

3

has

can

4

this

 

that

Advanced Example

Now let us take a more real time example where we have a series of Employee objects having Id, Age and Name as the properties. We need to create a lookup list based on their age. The result will be having Age as key and the corresponding Employee objects.

private void ToLookupAdvanced_Click(object sender, EventArgs e)

{

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

list.Add(new Employee() { Id = 1, Age = 20, Name = “Kavin” });

list.Add(new Employee() { Id = 2, Age = 30, Name = “Alen” });

list.Add(new Employee() { Id = 3, Age = 20, Name = “Suresh” });

list.Add(new Employee() { Id = 4, Age = 30, Name = “Jay” });

list.Add(new Employee() { Id = 5, Age = 20, Name = “Nanda” });

ILookup<int, Employee> lookupList = list.ToLookup(employee => employee.Age);

foreach (Employee employee in lookupList[20])

MessageBox.Show(employee.ToString());

}

The result of the above code will be Employee objects with Age = 20:

1 Kavin

3 Suresh

5 Nanda

The class structure of Employee would be:

public class Employee

{

public int Id;

public double Salary;

public int Age;

public string Name;

public override string ToString()

{

return this.Id.ToString() + ” ” + this.Name;

}

}

Extension Method Snapshot

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

clip_image002

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

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.

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

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.

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

One Line Lambda – To select last 3 items in the list and find sum

Posted by Paul on December 5, 2010

Here I am trying to show the advantage of Lambda Expression in code reduction and time saving.

Scenario

You have got a list containing 10 items.

1

2

3

4

5

6

7

8

9

10

You need to get the sum of last 3 items in the list.

Normal Approach

In a normal approach, we have to start from the last item in a for loop and decrementing the index variable. 

IList<int> list = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });

int sum = 0;
for (int i = list.Count – 1; i >= list.Count – 3; i–)
      sum += list[i];

Lambda Approach

The same functionality can be applied in a single line using the inbuilt methods Reverse(), Take() and Sum().

// Single line of code to attain the above task

int sum = list.Reverse().Take(3).Sum();

Code Explained

The method Reverse() reverses the list

The method Take() takes the specified number of items

The method Sum() performs the sum operation

Summary

In the above scenario, Lamba helped us from

  1. Little hectic code of for loop and decrementing index
  2. Reduced the number of lines from 3 to 1
  3. Helped in attaining the functionality in ease

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

One Line Lambda – To select last 3 items in the list and find sum

Posted by Paul on December 5, 2010

Here I am trying to show the advantage of Lambda Expression in code reduction and time saving.

Scenario

You have got a list containing 10 items.

1

2

3

4

5

6

7

8

9

10

You need to get the sum of last 3 items in the list.

Normal Approach

In a normal approach, we have to start from the last item in a for loop and decrementing the index variable. 

IList<int> list = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });

int sum = 0;
for (int i = list.Count – 1; i >= list.Count – 3; i–)
      sum += list[i];

Lambda Approach

The same functionality can be applied in a single line using the inbuilt methods Reverse(), Take() and Sum().

// Single line of code to attain the above task

int sum = list.Reverse().Take(3).Sum();

Code Explained

The method Reverse() reverses the list

The method Take() takes the specified number of items

The method Sum() performs the sum operation

Summary

In the above scenario, Lamba helped us from

  1. Little hectic code of for loop and decrementing index
  2. Reduced the number of lines from 3 to 1
  3. Helped in attaining the functionality in ease

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

One Line Lambda – To remove items in a list

Posted by Paul on December 5, 2010

I would like to show the advantage of Lambda expressions in time and coding effort saving

Scenario

You are given a list of integers:

1

2

3

4

5

6

2

8

9

2

5

You need to remove the numbers 2 from the list:

The numbers are stored in IList<int> list;

Normal Approach

If you try to remove the object by using a foreach. It will result in the following exception.

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

foreach (int i in list)

if (i == 2)

list.Remove(i);

Error: Collection was modified; enumeration operation may not execute.

Another Approach

We can employ a while/for loop to achieve the same:

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

for(int i = 0; i < list.Count; i++)

if (list[i] == 2)

{

list.RemoveAt(i);

i–;

}

The code above works fine. But seeing the lambda approach below you can feel the reduced coding effort.

Lambda Approach

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

list = list.Where(i => (i != 2)).ToList<int>();

// Here we are selecting the numbers which are not equal to 2 and

// converting the result into a new list

Output

The output of the application will be:

1

3

4

5

6

8

9

Note

Lambda Expressions are really powerful tool, which results in reduced code and saving time. It is really investing at the cost of just 10 minutes learning curve involved.

There are tons of fun code associated with Lambda Expressions awaiting you!!

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

One Line Lambda – To remove items in a list

Posted by Paul on December 5, 2010

I would like to show the advantage of Lambda expressions in time and coding effort saving

Scenario

You are given a list of integers:

1

2

3

4

5

6

2

8

9

2

5

You need to remove the numbers 2 from the list:

The numbers are stored in IList<int> list;

Normal Approach

If you try to remove the object by using a foreach. It will result in the following exception.

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

foreach (int i in list)

if (i == 2)

list.Remove(i);

Error: Collection was modified; enumeration operation may not execute.

Another Approach

We can employ a while/for loop to achieve the same:

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

for(int i = 0; i < list.Count; i++)

if (list[i] == 2)

{

list.RemoveAt(i);

i–;

}

The code above works fine. But seeing the lambda approach below you can feel the reduced coding effort.

Lambda Approach

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

list = list.Where(i => (i != 2)).ToList<int>();

// Here we are selecting the numbers which are not equal to 2 and

// converting the result into a new list

Output

The output of the application will be:

1

3

4

5

6

8

9

Note

Lambda Expressions are really powerful tool, which results in reduced code and saving time. It is really investing at the cost of just 10 minutes learning curve involved.

There are tons of fun code associated with Lambda Expressions awaiting you!!

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

How to map a command to method without using if/switch?

Posted by Paul on November 26, 2010

Here I am trying to show the advantage of using Lambda expressions along with some built in delegates.

Scenario

The user will input a command like “MoveUp”, “MoveDown”, “TurnLeft”, “TurnDown”.  Based on the commands, you have to call the the methods MoveUp(), MoveDown(), TurnLeft(), TurnDown() respectively.

The old code will look like:

string command = "Move";

 

if (command == "MoveUp")

    MoveUp();

else if (command == "MoveDown")

    MoveDown();

else if (command == "TurnLeft")

    TurnLeft();

else if (command == "TurnRight")

    TurnRight();

We can replace the same code with Lambda and built-in delegate Action as:

string command = "Move";

 

IDictionary<string, Action> actions = new Dictionary<string, Action>();

actions.Add("MoveUp", MoveUp);

actions.Add("MoveDown", MoveDown);

actions.Add("TurnLeft", TurnLeft);

actions.Add("TurnRight", TurnRight);

 

actions.Where(a => a.Key == command).FirstOrDefault().Value();

Note: The Action is a built-in delegate with void as return and no arguments input.  There are total of 4 versions of Action.

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