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 May, 2011

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

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 »

MSDN Forums :: 4000+ Points with 200+ Answers completed

Posted by Paul on May 24, 2011

Thank you for visiting this page.  Here I would like to showcase my MSDN Forum contributions in fixing and answering queries.  I have been working on the following categories for past 2 years.

  1. Visual C# General
  2. Visual C# Language
  3. .Net Base Class Library
  4. SharePoint 2010
  5. Windows Forms
  6. Windows Communication Foundation

Please view my MSDN Profile here:

After all it is really fun to be there on the Forums.  You can find lots of programming scenarios which you never encountered and resolving them will make us learn more and sharpen the skills.  Plus on the other side our dearest friend will be happy about getting the problem resolved.

So that’s the reason I kept my forum caption as – “Resolving n Evolving!”

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

MindCracker MVP Awards 2010, 2011, 2012

Posted by Paul on May 24, 2011

It was my pleasure to get the MindCracker MVP Award consecutively for 3 years.  The award was given for my contribution towards Articles and Forums in c-sharpcorner.com – a great site for .Net resources.

You can see the awards here:

  1. MindCracker MVP 2011

  2. MindCracker MVP 2010

I would like to thank all the supporters who encouraged me in posting articles and so..  I would like to thank the site leaders Mahesh Chand and Praveen Kumar for providing me this great platform.  Plus thanking my friend Dhananjay Kumar for guiding me to learn the ropes.

Posted in C# | 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 »

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 »