Jean Paul's Blog

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

  • 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

Posts Tagged ‘lambda expression’

Lambda Expressions Extension Methods Series 11 -SequenceEqual()

Posted by JP on November 13, 2011

In this small article, I would like to introduce the SequenceEqual() method. This method is very handy to compare two IEnumerable and return a Boolean stating whether each elements of both IEnumerable are same or not.

Method: SequenceEqual()

Arguments: IEnumerable<>

Operates On: IEnumerable

Returns: True/False

Example

Let us have two lists of integers.

List 1 having

1

2

3

List 2 having

1

2

3

Here both the list are of same elements. We can use the SequenceEquals() method to view the result:

bool result1 = list1.SequenceEqual(list2);

Output

The output of the above code will be:

True

Code Explained

Here on calling the SequenceEquals() method, each element of list1 is compared with corresponding element of list2. The default Equals() comparison is exercised here.

Elements of primitive types will have value comparison and

Elements of class types will have reference comparison (unless they override the Equals() method)

Sample Code with int and object Scenarios

// Creating list of int

IList<int> list1 = new List<int>() { 1, 2, 3 };

IList<int> list2 = new List<int>() { 1, 2, 3 };

IList<int> list3 = new List<int>() { 4, 5, 6 };

bool result1 = list1.SequenceEqual(list2); // True

bool result2 = list1.SequenceEqual(list3); // False

// Creating employee objects

Employee employee1 = new Employee() { Id = 1, Name = “Employee1” };

Employee employee2 = new Employee() { Id = 2, Name = “Employee2” };

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

list4.Add(employee1);

list4.Add(employee2);

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

list5.Add(employee1);

list5.Add(employee2);

bool result3 = list4.SequenceEqual(list5); // True – As Same ref of Employee objects

The Employee class would be having following structure:

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;

}

}

Advertisements

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

Lambda Expressions Extension Methods Series 9 – OfType()

Posted by JP on November 13, 2011

Then Enumerable.cs provides extension method OfType(). It can be used to select elements in an IEnumerable based on the type.

Method: OfType()

Arguments: None (Has Generic Argument)

Operates On: IEnumerable

Example: We have a list of objects, containing integer, float, string and character items. The OfType() method can be used to get elements which are integer.

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

list.Add(1);

list.Add(1.1);

list.Add(2);

list.Add(2.2);

list.Add(“string”);

list.Add(‘c’);

In order to select the elements which are int – the following code can be used.

var result = list.OfType<int>();

Here the OfType() method takes an int generic argument.

Output

The output of the above code will be:

1

2

Code Explained

In the above code we are having the following elements as inputs:

Element

Type

1

Integer

1.1

Float

2

Integer

2.2

Float

“string”

String

‘c’

Character

Extension Method Snapshot

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

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

Lambda Expressions Extension Methods Series 10 – Min, Max, Sum, Average

Posted by JP on November 13, 2011

Lambda Expressions Extension Methods Series 10 – Min, Max, Sum, Average

The Extension Methods also include the following 4 calculation methods – Min, Max, Sum and Average() for calculating the minimum value, maximum value, sum and average respectively.

Method

Description

Min()

Calculates the minimum value in the series

Max()

Calculates the maximum value in the series

Sum()

Calculates the sum of the values

Average()

Calculates the average of the values

The above methods saves a lot of time and code by discarding the need of creating a variable and for loop to iterate through the elements to find the Minimum, Maximum, Sum and Average of the items.

Example

The sample list would be a list of integers from 1 to 6.

public InitializeLIst()

{

InitializeComponent();

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

The test code will be as following:

private void MinMaxSumAvgButton_Click(object sender, EventArgs e)

{

int min = _list.Min();

int max = _list.Max();

int sum = _list.Sum();

double average = _list.Average();

string message = “Min={0}\nMax={1}\nSum={2}\nAverage={3}”;

MessageBox.Show(string.Format(message, min, max, sum, average));

}

On execution of the code above we can see the output as below:

Extension Method Snapshot

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

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

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

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

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

Lambda Expressions Extension Method 8 – Select() with Anonymous Type Creation

Posted by JP on November 13, 2011

Select() with Anonymous Type Creation


As a continuation of Select() method, we can have anonymous type creation as well.  The anonymous type are those without a name in our c# source code and the compiler will generate an automatic name for it.

It is convenient that we are free from creating a class and properties.  The following example shows

  • How to specify an anonymous class  in the Select Method
  • How to create the properties of anonymous class
  • How to retrieve the properties of anonymous class

Parameters: Input type and Transformation Method
Return Value: List of Items

Example

In the following example we are using a list of integers and converting them to a class having 2 properties:

  • Value which is the actual value of integer
  • Index which is the index of the element

The statement _list.Select((i, ix) => new { Value = i, Index = ix }) will do the job.

After converting we are storing the result in a var type.

For retrieving the properties back we use the same var keyword and iterate through a foreach.  The var type allows us to read the properties Value and Index with automatic type inference by IDE.

Code

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 SelectAnonymousButton_Click(object sender, EventArgs e)
  {
  var result = _list.Select((i, ix) => new { Value = i, Index = ix });

  foreach (var v in result)  {
  string messsage = "Value={0} at Index={1}";
  MessageBox.Show(string.Format(messsage, v.Value, v.Index));
  }
  }

Input
1
2
3
4
5
6
Output
“Value=1 at Index=0”
“Value=2 at Index=1”
“Value=3 at Index=2”
“Value=4 at Index=3”
“Value=5 at Index=4”
“Value=6 at Index=5”
Extension Method Snapshot

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

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

Lambda Expressions Extension Method 7 – Select()

Posted by JP on November 13, 2011

Select() Extension Method

The Select() is a straight forward method. It converts the argument from one type to another type.

For eg: If we need to convert a list of integers to string, we can achieve that using Select() as given below.

Similarly we can use value types to custom class conversions, to anonymous type conversions etc.

Parameters: Input type and the Transform Functions

Return Value: List of Items

Example

In the following example we are using a list of integers and the Select() method to convert each elements in the list.

Code

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 SelectButton_Click(object sender, EventArgs e)

{

var result = _list.Select(a => a.ToString());

foreach (string s in result)

MessageBox.Show(s);

}

Input

1

2

3

4

5

6

Output

1

2

3

4

5

6

(Converted to string)

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

Lambda Expressions Extension Method 6 – SkipWhile()

Posted by JP on November 13, 2011

SkipWhile () Extension Method

The SkipWhile() is a tricky method. It takes one condition as argument and iterates over the elements. It will start returning the elements once the condition turned false. It will continue returning the elements until the end of the loop.

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

First it will take element 1 and as the condition is evaluated to true – it will skip the element.

It will go until element 5, and the condition turns false – then from current element onwards it will return all remaining elements.

Parameters: Condition

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 SkipWhileButton_Click(object sender, EventArgs e)

{

/// SkipWhile method to get a sublist by skipping elements if condition is

/// true and continuing till end without checking condition.. Little tricky

var result = _list.SkipWhile(i => (i != 5));

foreach (int i in result)

MessageBox.Show(i.ToString());

}

Input

1

2

3

4

5

6

Output

5

6

Extension Method Snapshot

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

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

Grouping using Lambda Expressions

Posted by JP 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;
}

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

Lambda Expressions Extension Methods Series 12 – ToLookup()

Posted by JP 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 JP 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 JP 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 »