Sunday, June 30, 2013

LINQ 10- Projection/Select- 1

Select method provides a way to transform each element to a desirable format.

Following code does nothing but gives a enumerable list of the source.

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Select(number => number);

 

Let try a simple transformation like getting the numbers doubled

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<int> selected = numbers.Select(number => number * 2);
foreach (var item in selected) {
    Console.WriteLine(item);
}
Console.ReadKey();

 

Above code returns a Enumerable set of integers with values doubled from the source.

So you will get result 2,4,6,8,10

 

Select method is declared in System.Linq.Enumerable class as

public static IEnumerable<TResult> Select<TSource, TResult>

(this IEnumerable<TSource> source,

Func<TSource, TResult> selector);

 

Here TSource is automatically identified from the input enumerable. As we are using Integer Array, TSource is identified as Integer.

 

TResult is identified from the delegate or lambda expression passed to the method. As we are returning just the doubled number TResult is also identified as Integer.

 

Consider the following example which returns a String.

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
IEnumerable<String> selected = numbers.Select(number => (number * 2).ToString());
foreach (String item in selected) {
    Console.WriteLine(item);
}
Console.ReadKey();

 

As we are returning the string TResult is identified as String, hence the select returns IEnumerable<String>

Tuesday, June 25, 2013

LINQ 09- LINQ Extensions

As we discussed earlier in "LINQ 08- IEnumerable", LINQ works with IEnumerable interface along with many extension methods. These extension methods are available in System.Core assembly in .Net Framework 4.0. You can find several extension methods available in the class System.Linq.Enumerable

 

So If you are going to use LINQ queries, you have to add System.Core as a reference and add “using Sytsem.Linq” to your imports.

 

Reference: Enumerable Class

Wednesday, June 19, 2013

LINQ 08- IEnumerable

LINQ is designed to work with collections. Common use of collection is iterating through them to read, filter and manipulate them.

Following diagram shows the flow which is commonly used for reading all items with IEnumerable

IEnumerable flow

 

Foreach loop uses the same logic to iterate through items in collections. Behind the scenes .Net  uses IEnumerable for iterating through collections. All the collection classes (from arrays to generic lists) are implemented using IEnumerable. So IEnumerable interface is unavoidable for every .Net programmer.

 

LINQ extends the concept of IEnumerable with extension methods to provide LINQ queries. Even without LINQ, the extension method provides many collection operations like searching, transforming, grouping and ordering using IEnumerable interface.

 

Sample Code

var a = new int[] { 1, 2, 3, 4, 5 };
var e = a.GetEnumerator();
while (e.MoveNext()) {
    Console.WriteLine(e.Current.ToString());
}

Wednesday, June 12, 2013

LINQ 07- Anonymous Types

Anonymous types allows users to create objects without creating classes. In many cases, we may need to store compound related data, but that will be referred in within a particular method. In .net framework 2.0, anonymous types, we have to write a simple classes and properties to achieve this.

Anonymous types works with Automatic Type Inferencing, Auto Implemented properties and Object Initializers

Example

var e = new {
    ID = 10,
    Name = "John",
    Designation = "Software Engineer",
    Age = 25
};

 

C# Compiler implicitly creates a type and uses it.

Notes:

  • As the type name is unknown, automatic type inferencing should be used.
  • As Automatic type inferencing is the only option to declare anonymous types, it can be used within code blocks only, can not be used as type member
  • Anonymous types with same properties with same property types are considered as equal.

Hence

var e = new {
    ID = 10,
    Name = "John",
    Designation = "Software Engineer",
    Age = 25
};

and

var f = new {
    ID = 11,
    Name = "Mike",
    Designation = "Software Engineer",
    Age = 26
};

are considered as same type.

  • Arrays with anonymous type elements can be created as

var e = new[]{ new {
    ID = 10,
    Name = "John",
    Designation = "Software Engineer",
    Age = 25
},
new {
    ID = 11,
    Name = "Mike",
    Designation = "Software Engineer",
    Age = 26
}};

  • It is not possible to refer property values within declaration. Following statement is WRONG.

var e = new {
    ID = 10,
    FirstName = "John",
    LastName ="Carter",
    FullName = FirstName + " " + LastName,
    Designation = "Software Engineer",
    Age = 25
};

Saturday, June 08, 2013

LINQ 06- Automatic type inferencing

Automatic type inferencing allows you to declare variables without specifying the type before the variable name.

You don’t have to specify the exact type when initializing variable with a type specific value

Example:

Instead of

int i = 10;

you can use

var i = 10;

 

Same can be used for objects to

var e = new Employee();

In case you want a base class type to be used for the variable, you can use casting.

var p = (new Employee()) as Person;

 

Note:

    • This can only be used inside a code block (methods, property get set blocks, etc)

Wednesday, June 05, 2013

LINQ 05- Object Initializers

Object initializer provides a shortcut to initialize an object with property values.

Considering the following class.

public class Employee {
    public Employee() {
       
    }
    public Employee(int id) {
        this.ID = id;
    }
    public int ID { get; set; }
    public string Name { get; set; }
    public string Designation { get; set; }
}

 

With object initializer, we can initialize an Software Engineer John with ID 10, in one statement.

var e = new Employee() {
    ID=10,
    Name="John",
    Designation="Software Engineer"
};

or

var e = new Employee(10) {
    Name="John",
    Designation="Software Engineer"
};

Second example shows the initialization of a class with parameterized constructor.

Tuesday, June 04, 2013

LINQ 04- Auto implemented properties

While writing properties to classes, mostly we declare a variable and expose it through properties.

public class Employee {
    private int id;
    public int ID {
        get { return id; }
        set { id = value; }
    }
}

Auto implemented properties help to reduce the code by implicitly doing the field declaration, return and assignment through get and set of the properties.

 

With auto implemented properties, above code can be optimized as

public class Employee {
public int ID { get; set; }
}

Notes:


Properties type is used for the implicit variable.


Implicit variable will be declared as private.


Automatically implemented properties must define both get and set accessors


We can use separate access modifier for get or set. (public int ID { get; private set; })

Sunday, June 02, 2013

LINQ 03: Lambda expression

Lambda expressions provides a simpler mechanism, to create or pass delegates without creating a separate methods to be referred.

In other words, we can say lambda expressions are inline functions

 

For example consider the following

we have a delegate CalcDelegate with two integer parameters

delegate void CalcDelegate(int a, int b)

we have a method Calc requires the CalcDelegate to be passed.

int Calc(CalcDelegate, int m, int n)

To create an Add operation with this, we will create a add method

void Add(int a, int b) {return a+b;}

So that we can call the Add using Calc

Calc(Add, 1, 5);

But for using in a single location, we have to create a function for this (without lambda expressions)

With lambda expressions we can simplify this with the inline method

Calc( (a,b) => a+b, 2, 5);

 

Lambda expressions are simple to create

left side of => is the parameter section

right side of => is the body section

 

Parameter section

  • when no parameters are required for the delegate, we can use ()
    • Example: ()=> Console.WriteLine(‘no parameter method invoked’)
  • when only one parameter is required for the delegate, we can use paramName or (paramName)
    • Example: a=> a*2
  • when more that one parameters are required for the delegate, we can use (paramName1, patamName2, …)
    • Example: (a, b) => a +b
  • Parameter types are inferred with automatic type inferencing
  • When the automatic does not help, we can use explicit declaration (paramType1 paramName1, paramType2 paramName2, …)
    • Example: (int a, int b) => a + b

Body section

  • When the function has single statement, no need for open and close braces, but we can use them optionally.
    • Example: a=> a*a
  • When the function has multiple statements we should enclose them within open and close braces
    • Example: a=> { var b=a*a;  return b;}