What Are New LINQ C# Features

Inroduction

In this article, we’re going to learn C# features for LINQ language integrated query. So, we’re going to understand about the Extension methods, Lambda Expressions and Expression Trees. And then we’re going to understand the ways to write LINQ queries in C#. The first syntax is Link Comprehension Query Syntax and the second syntax is Extension Method Syntax. And some people alSo, refer to it as the Lambda Expression Syntax. And then we’ll see the some features that make LINQ more enjoyable and C# and that is type inferencing Anonymous Types and Partial Methods.

Extension Methods

The Extension methods allow you to add a new instance. when appears to be new instance methods to an existing type even if that type is a sealed class or with an interface. So, this isn’t inheritance and this isn’t changing in the code of that type, this is going to be adding a method that appears to be an instance method.

So, let’s understand the following example. the StingToDouble class in C# at one point or another. But, if we find ourselves having to parse doubles out of stings a lot create a static class called StingToDouble or string helpers or add a static method to that called ToDouble. where you pass in a string and then it’ll do the work to pull out a double.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqExample
{
  public static class StingToDouble
 {
   static public double ToDouble(string data)
   {
     double result = double.Parse(data);
	 return result;
   }
 }
}
string value = "11.14";
double data = StingToDouble.ToDouble(value);

So, With the extension methods what you do is add a “this” keyword or a modifier to the first parameter of that method. Once we’ve done that the magic is that we can walk up to a string and invoke this ToDouble operation. as if we’re an instance method on the string class itself which is you now have the string as a built-in type in the .NET framework. so, we can’t go in and change the code to add a method like that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqExample
{
  public static class ExtensionExample
  {
   public static bool Tovalidate(this string data)
   {
	 return data.Length == 4 || data.Length == 6;
   }
 }
}

Now, a couple of things to know about extension methods, you must define them inside of a static class. and it cannot be a class that takes type parameters, generic type parameters. And don’ think that once you write and Extension Method you’ll gain access to an object’s private interstate.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqExample
{
  class Program
  {
   static void Main(string[] args)
   {
	 string number = "123456";
	 
	 bool IsLength = ExtensionExample.Tovalidate(number);//case 1
	 
	 bool IsLength2 = IsLength.Tovalidate();// case 2
   }
 }
}

Lambda Expression Essentials

The Lambda Expression is all about syntax, it is a compact way of representing an anonymous method. that is a little block of code that expresses that the behavior that we need some operator to perform. So, this can use with LINQ. Let’s look at this with a different example.

So, here is IEnumerable of string. we want all the cities that StartWithL and it implement a named method. that would actually implement that behavior that predicate.

Named Method:

IEnumerable<string> filteredList = Countries.Where(StartWithM);

public bool StartWithM(string name)
{
   return name.StartWith("M");
}

Anonymous Method:

And then in c# 2. 0 when we had anonymous methods we could express that in line with a delegate so we could write a delegate.

IEnumerable<string> filteredList = Countries.Where(delegate(string s){ return s.StartWith("M"); });

Lambda Expression

The Lambda Expression allow us to do with a link provide a concise way of expressing the behavior. that, we want the where operator to perform. So, the where operator that going through the enumeration of strings can invoke the little expression and in this case it’s M goes to M that starts with M.

IEnumerable<string> filteredList = Countries.Where( c => c.StartWith("M"));

Now, a couple of things to know about Lambda Expressions

1] this is a very functional programming style and underneath the covers, they are still an anonymous method.

2] if you use a Lambda Expression and Compile a program and open it up with a decompiler like a reflector. what you’ll see is anonymous method definitions with delegate keywords.

3] We don’t need a return keyword and we also don’t need type names and curly braces and semicolons and so forth.

4] The left-hand side of this operator a function signature. On the right-hand side is an expression.

Query Expressions

Now, we know that LINQ defines all its standard operators as extension methods. either for IEnumerable of T or IQueryable of T so that’s where we get the standard operators from. And we’ve seen how Lambda Expressions can shorten the behavior that we need to pass into these operators. The query expressions begin with a from clause, end with a select or group.

string[] countries = { "Koria", "United States", "Malaysia", "Japan", "Germany"};

IEnumerable<string> filteredCountries = from country in countries where country.StartWithM("M") && country.Length < 15
orderby country select country;

Implicit Typing or Type Inference

The implicit typing uses the “var” keyword, it looks like the var keyword in JavaScript. but, the sense that JavaScript uses weak dynamic typing and it can say var x equals and some string and then on the next line of code assign x an integer value and JavaScript’s. Variables that you declare with the var keyword in C# are strongly tight.

var name = "John";
var val1 = 4.4;
var val2 = 5;
var val3 = val1 * val2;

Console.WriteLine(name is string);
Console.WriteLine(val1 is double);
Console.WriteLine(val2 is int);
Console.WriteLine(val3 is double);

The var keyword does is allow the C# compiler to infer the type of the variable based on how you’re using it. So there’s a couple of rules here. First of all the C# compiler doesn’t know how to type this variable. because there’s no initialization value for it. So it’s going to sting, going to be a number. So it’s going to be a compiler error. And you also can’t have many declarators. Null is not a good value to initialize a var value because the C# compiler left that as an error. And finally, JavaScript will be reasonable to get something else and say number plus 1. But in C# this is going to disallowed, the number is a string, that’s what assign it, it’s forever going to be a string. And we can’t convert strings into integers without being explicit about it.

Anonymous Types

So, The Anonymous methods are blocks of code that have no names. Anonymous types are the same concept. They are types that do not have names. And this is where the var keyword plays a main role. here, we have following block of code

var employee = new { Name = "John" , Salary=60000 };

Console.writeline("{0}:{1}",employee.Name, employee.Name);

First of all, we’re using the var keyword which means the C# compiler is going to infer the type of employee and that’s easy enough for it to do.

The anonymous types they always derive from System. Object. Another thing is they are immutable types that are the properties, this is going to given Name and Salary properties are going to read-only properties. So you can set them during construction and after that, there’s no more filling around with them. You can only use anonymous types in the var keyword inside of a method definition. so it has to be for a local variable.

Initializers

Another feature added to C# 3. 0 to try to shorten up the amount of code you need to write in certain scenarios was the idea of Initializers. And we have Initializers for both objects and for collections.

So here, we have an Employee class to find, we have an Address class to find. If we wanted to construct a new Employee what the class Initializer. lets us do is we no longer have to write a constructor for that Employee that accepts a parameter for every property that needs to be set.

public class Employee
{
  public int ID {get; set;}
  public string Name { get; set;}
  public Address MyAddress {get; set;}
}

public class Address
{
  public string City { get; set;}
  public string Pincode {get; set;}
}

here, we’re going to create instance for employee and employee list.

Employee employee = new Employee { ID=11, Name="Robin", MyAddress = { City="Hongkong" , Pincode=121 }  };

List<Employee> Emplist = new List<Employee>() {
 new Employee { ID=11, Name="Robin", MyAddress = { City="" , Pincode=123 }  },
 new Employee { ID=12, Name="James", MyAddress = { City="" , Pincode=124 }  }
 new Employee { ID=13, Name="John", MyAddress = { City="" , Pincode=121 }  }
};

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *