WHAT'S NEW?
Loading...
Showing posts with label linq. Show all posts
Showing posts with label linq. Show all posts

Index


  • Introduction
  • Linq features
  • Linq queries
  • Linq under the hood
  • Linq to XML
  • References

Introduction

This post is part of a series of post to help you prepare the MCSD certification, particularly the certification exam 70-483, based on the book:


You will find all the code available in the following GitHub repository. Lets talk a little bit about threads and how they work using a .Net development environment.

Linq features

Linq aka Language-Integrated Query was introduced with C# v3.5 and it's a widely language used to query data. There are some features in the language that make Linq possible:
  • Implicitly typed variables: this happens whenever you define you variables using the keyword "var" instead of doing an explicit type definition. This is necessary using Linq because sometimes you can't specify the return explicitly because you don't know it. It makes you code more readable as well.
  • Object initialization syntax: it enables you to combine creating a new object and setting its properties in one statement and this is required when working with anonymous types.
  • Lambda expressions: before lambda expressions, it's necessary to have clear what anonymous methods are (delegates). They were introduced in C# v2.0 to create, assign and pass methods in one line. 
    • .Net introduced shorthand 
      • Func<T,T> and 
      • Action<...> (returns nothing) to simplify the creation process. 
    • Lambdas use the => notation which can be read as "becomes".
    • Linq often has to pass a Func<> delegate to a method.
  • Extension methods: Extend an existing type with new behavior without using inheritance. It uses the special "this" keyword to mark itself as an extension method. Linq is entirely based on extension methods.
  • Anonymous types: this is a mix between implicit typing and object initializes. You create an anonymous type by using "var" and the new operator without specifying a type. This is used in Linq when you create a projection, so you select certain properties from a query and form a specific type.

Linq queries

There are two ways to query data with Linq: Query syntax or Method syntax, ie:


Linq query operators: these are the different actions we can perform over our data and that we know is implemented in other providers like Linq to XML, Linq to entities, Linq to Objects. Here are some: All, Any, Average, GroupBy, Join (it's used to combine data from two or more sources by specifying the property that needs to be equal), Max, Min, OrderBy, Select, Skip, Take (skip/take are used to add pagination, ie: when you call a db and you want to split the answer in pages so performance is not affected), Where...

Other useful features are projection (select) and grouping (groupBy). Projection is used to select another type or an anonymous type as the result of your query. Grouping, you group your data by a certain property and then work with that result.

If you want to test your queries there's a nice tool called linqpad which can help you to create a playground where do your experiments. 

Linq under the hood


As you already know how extension methods is used in Linq you might want to change the behavior of one of the operations provided. Then you have to remove the using System.Linq statement and try with the following approach:


Here you'll see how an iterator pattern is implemented. By using "this" we are extending the behavior of our method. The "yield" parameter is used to return values but one at a time. This is called "deferred execution".

This is important when you work with other Linq providers like Linq to entities or linq to SQL (it parses the query and transform it to SQL). The query won't be sent to the database until the result is iterated over. Iterating can happen when you call ToList() or when you iterate over the results in a for each statement (which calls the MoveNext() method).

Linq to XML

In previous lessons we've already talked about how to access XML files. Here I want to show you another approach. XDocument class is used to load a file, it works with the XNode abstract class. You can also use XDocument.Descendants or XDocument.Elements as well as XDocument.Nodes to access the child of a node. All those elements grant you access to the attributes within a node.

It also allows you to create your own XML. By calling the Add() method you can start building your file or in another way, you can use the XElement constructor that takes an array of objects that form the content.

Finally, in order to update your XML files you have two approaches:
  1. procedural way: it basically consists on building your objects one by one and then attach them to the xml structure.
  2. functional construction: it consists on using LINQ to XML syntax to find the bits you want to modify and update them with the new values.
It depends how difficult is your transformation whether you use functional or procedural transformations, If the XML structure changes the functional has a lot more benefits.

Index

  • Intro
  • Async and Await
  • What is a database
  • What is LINQ
  • LINQ Demo

Intro

Let's talk today about data. Bring data is typically a high cost operation that's why we need to use always the perfect data storage system regarding our requirements. There are techniques like asynchronous communications which will help us on speeding our systems. How to retrieve that data is an important subject and decide which approach to use will be also discussed.


Async and Await

Async and await simplify asynchronous programming in .Net. Async and await allow asynchronous code to resemble the structure of synchronous code. Methods marked with async may return Task as the Task-based Asynchronous Pattern (TAP) defines. The async keyword instructs the compiler to allow await. The await keyword instructs the methods to return The await keyword instructs the compiler to resume execution within the same context after the operation is complete. 

In the following example we run an asynchronous operation in our call to DownloadStringAsync which is defined within the WebClient component in the .Net framework. This functions performs some operation in background, which means, the execution process in our app is never stopped. We don't know when this task will be completed, that's why we've published an event called "Completed" which a class can subscribed to and be notified when the completion occurs.



using System;
using System.Net;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class AsynchronousExample
    {
        public event EventHandler Completed;

        void GetHtml(string url)
        {
            var client = new WebClient();
            client.DownloadStringCompleted += client_DownloadStringCompleted;
            client.DownloadStringAsync(new Uri(url));
        }

        private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (Completed != null)
                Completed(this, e);
        }
    }
}


In our next example we are using the reserved word "async" to decorate our method. See the type returned here is a Task. This means when we trigger probably a long running process which will return immediately a Task object. It won't stop to the completion of the asynchronous method. This task object will contain the result but it will be uncompleted until the DownloadStringTaskAsync finishes.


using System;
using System.Net;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class AsynchronousExample
    {
        private async Task GetHtmlWithAsync(string url)
        {
            var client = new WebClient { };
            return await client.DownloadStringTaskAsync(new Uri(url));
        }
    }
}

What is a database

  • A database is a data store
  • Data stored in a database is structured
  • Data stored in a database may be related (Referential integrity)
  • A database provides a way to access / query data (Optimized by indexes)

SQL DB Types

  • Windows Azure SQL Database
  • Local Network SQL Database
  • Local Machine SQL Server Express 
  • Application SQL LocalDB
  • Application SQL CE
  • Other providers: Oracle, SqLite, MySql, DB2

Types of access to a database: how do we talk to the database
  • Low-Level
    • Manual queries
    • DbDataReader
  • Object Relationship Models (ORM): allow you to conceptualize the model of you db.
    • Entity Framework
    • nHibernate

What is LINQ

Language Integrated Query:

  • is a general-purpose Query Language
  • is an integrated part of the .Net languages
  • is Type Safe and has Intellisense
  • includes operators like Traversal, Filter and Projection
  • can be optimized with compiler versions
  • can be invoked using its Query Syntax
  • can be invoked using its Method Syntax

LINQ Demo

See here enclosed some examples about how to use the LINQ library in a .Net environment. I'll try to show you how to get the even and odds number from a list. Then we'll move forward sorting a bunch of letters in a handy way

var data = Enumerable.Range(1, 50);

// even or odd
// method syntax
var method = // IEnumerable
    data.Where(x => x % 2 == 0)
        .Select(x => x.ToString()); // Projection: take data and transform it into text

// query syntax
var query = // IEnumerable
    from d in data
    where d % 2 == 0
    select d.ToString();

var projection =
    from d in data
    select new
    {
        Even = (d % 2 == 0),
        Odd = (d % 2 != 0),
        Value = d,
    };


I'm using different approaches in order to get odd's and even numbers. I'm presenting the result in different ways also. For the method and the query variable, I'm storing the values as strings. Within the projection variable, I'm actually creating small structures containing three values, the first two save a boolean true/false and the last one stores the current value.

var letters = new[] { "A", "C", "B", "E", "Q" };

// query syntax
var sortAsc =
    from d in data
    orderby d ascending
    select d;

// method syntax
var sortDesc =
    letters.OrderByDescending(x => x);


var values = new[] { "A", "C", "A", "C", "A", "D" };

var distinct = values.Distinct();   // remove duplicates
var first = values.First();         // error if "values" is empty
var firstOr = values.FirstOrDefault();  // default if "values" is empty
var last = values.Last();
var page = values.Skip(2).Take(2);


See how in the previous example I'm working with a couple of character lists. For the first list I sort the characters using linq query sintax and linq method syntax respectively. For the last list, I wanted to show you the potential of  this language which allows you to performs actions like, remove duplicates, get the first/last or even skip some values and take more than one.

Really powerful library which I'm sure will help you to short out your code and present your future projects in a really professional way.

References

http://www.microsoftvirtualacademy.com/training-courses/developer-training-with-programming-in-c
https://msdn.microsoft.com/en-us/library/hh873175.aspx
https://msdn.microsoft.com/es-es/library/bb397926.aspx