Tech questions 1-3: Linq

0

Hey guys,

This is a new series I will try to maintain to the best of my capabilities. I’m this awesome blogger who happens to be also a Microsoft MVP called Iris Classon. After her first year of programming, she started to ask and get answers for what she’d call “stupid question”. Why would she consider them as stupid ? Well actually they’re not. They’re basically good questions that any developer, being a junior or an architect ( well less likely if you’re an architect), to ask and get answers too. Her series is really good and it got me thinking that I should start my own too. This begs the question to the why I would feel the need to do something like this for my blog ? We all want to get better in our field of expertise. Software engineering being extremely broad, it can get a “bit” confusing sometimes. My tech questions will lead me, I hope, to better myself and have not only a better understanding of the .NET framework, but any kind of technology that interest me right now or will interest me in a near/far future. I hope those questions will be helpful for the readers and followers of the blog.

To start the series, I will start with questions I have had in the past. Why ? It’s going to help me to stay on track and deliver answers for the tech questions on a regular basis. So let’s get cracking with LINQ. Why should we use LINQ in our C# solutions ? That’s quite a question. I cannot simply answer by the “well because it’s better that way.” and be done with it.

1. What is LINQ ?

The acronym LINQ stands for Language INtegrated Query. It allows .NET developers to query IEnumerable implementation to retrieve data as you would do in a SQL database. For instance, a list of int, which is a data structure implementing the IList interface which extends both ICollection and IEnumerable interface,  can be queried that list to see what’s the average of the values it contains. To be able to use LINQ, you’re going to add System.Linq directive in your source file (or have Resharper tell you exactly what references are missing from your code).

using System;
using System.Linq;
//Our very first linq call ! 🙂
public class LinqSamples
{
    public int AverageInts(List<int> list)
    {
        return list == null || list.Count == 0 ? 0 : list.Average();
    }
}

2. What are some benefits of LINQ?

Well there are many. You can bet that when you go LINQ, you won’t go back.  One of the first benefits of LINQ in your code is that makes it more declarative. This means that it can almost be read as plain English (as far as code goes).

using System;
using System.Linq;
public class LinqSamples
{
    //Worst name for a method I agree haha
    public List<string> OrderStringStartingByA_AndByLength(List<string> list)
    {
         return list.Where(str => str != null)
                    .Where(str => str.Contains("a"))
                    .OrderBy(strElement => strElement.Length);
    }
}

So basically, the method goes through the List to first manipulate only not null strings. Then it filters out of the list strings not starting by the letter ‘a’ and finally, orders the list by string length, from the smallest to the biggest string.

It can also reduce the complexity and the length code written using either a for or a       foreach loop. In order to write the equivalent of what I’ve just wrote using only foreach loops,  it would end up being something like :

using System;
using System.Linq;
public class LinqSamples
{
    //Worst name for a method I agree haha
    public List<string> OrderByA_AndLength(List<string> list)
    {
        var orderedList = new Lis<string>();
        foreach(var str in list)
        {
           if(str == null) break;
           if(!str.Contains("a")) break;
           orderedList.Add(str);
        }
        orderedList.Sort();
        return orderedList;
    }
    // See here : 9 lines vs 3 lines in the other example!
}

See here, we’ve been only using the type of LINQ called Linq to Object. The architecture was well thought; doing so, it lets pick up quite easily other types of LINQ such as LINQ to XML or LINQ to SQL.

3. What is a method group ?

In a few words, a method group is a set of overload methods resulting from a member lookup. This comes directly from the C# 3.0 Section 7.1. EventHandler handler = MyMethod; then “MyMethod” refers to a method group. There could be multiple methods with the same name, but different signatures. The method group conversion creates a delegate calling the appropriate actual method. In short, a method group is the name of a set method. There might just be one. Using proper conversions, the compiler will

A method group is the name for a set of methods (that might be just one).
The ToString function has many overloads – the method group would be the group consisting of all the different overloads for that function. It is a compiler term for “I know what the method name is, but I don’t know the signature”; it has no existence at runtime, where it is converted in the correct overload. Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup) so you can replace this code:

A method group is the name for a set of methods (that might be just one) – i.e. in theory the ToStringmethod may have multiple overloads (plus any extension methods): ToString(), ToString(string format), etc – hence ToString by itself is a “method group”. It can usually convert a method group to a (typed) delegate by using overload resolution – but not to a string etc; it doesn’t make sense. Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.

Hope you have enjoy this!
Kevin

Advertisements

First real life project : Managing orders

2

Welcome reader,

This post is a small break from the programming basics serie. I’m going to talk about a real life project I will talk about in this blog. It will be an open source project, which will be accessible from my GitHub account profile.  Before going talking more about the basics, I thought it would be a good idea to talk about what could be achieved when we will put everything that was learned and mastered here in this blog.

You have to create a software application which will store a large number of clients. These clients will make orders and they have to save in a database which must be available a least 95% of the time. Sometimes, special orders takes more time than usual before they come in, when this happens, you can either make it so that when it happens, you automatically send emails to users or u make a query in the database to select users and then send the email. For emails in this situation, you should have templates which would just receive dynamic data so the user of the software has less manipulation to do.

For users, the fun would be to have a self-contained mobile application . What I mean is this:

  • sign in into the app with all our information.
  • Be able to see whats going on in our account.

Moreover, while using a mobile device, such as a phone or a tablet, users would have notification of what going on. Even if emails are sent to the email account, it would even better to select what kind of feedback from the company a customer would like to receive.

In this example, we have a software application which must use a database. The information must be available at least 95 % of the time, so the fail rate has to be really low. The information on the orders must be available online so the users can access it from his mobile device with their app.

In our dev world, there are many ways to complete a task. What I recommend is usually go with what you know so you’ll know what you’re doing while you are doing it. But, in a realm in which things move faster than when oneself blinks his eyes, I think it would be a benefit to try out new technologies in order to gain experience.

For this kind of problem, I have chosen to use:

  1. C# with the object oriented paradigm
  2. Windows Phone (Universal App)
  3. The Android Operating System
  4. Reactive Extension (Rx)
  5. LINQ
  6. The Firebase database

Honestly, I haven’t really experimented the technologies #2, 4 and 6. But I’m not going into this series before we’re ready to do it. So during that time, I’ll get my hands dirty. In the developers community, when someone says getting their hands dirty, it is meant as programming. In order to understand something, we really need to experiment by ourselves, even if the code makes sense to you, I strongly suggest that you at least copy paste it into your IDE and run the application to see how it works on your machine. What would be best is to modify the code, play with it until you truly understand what’s going on.

On the topic of the open source project, I’m going to take you step by step in my solution. This is going a more advanced serie, but bear no fear, if there things that you don’t understand, post comments and I’ll answer you to the best of my knowledge. At first, we will setup our database before going into coding. Then, we’ll design our software application for the company. Then design our mobile app. Afterwards, when the designs are completed, I’ll explain the more complex parts of my implementation, but not all of it. You’ll be able to find the project on my GitHub. Don’t worry, it’ll be commented!

Kevin