Thursday, November 15, 2018

Tips and Tricks for modern C# - Efficient coding

Tip 1. using Enumerable.Range - generate a sequence


Flavor 1:
var list = Enmerable.Range(1,10) .ToList();

This is equivalent to the following code:


List list = new List();
for(int i=1; i<=10; i++)
{
     list.Add(i);
}

Rather than writing 4 lines of code to generate a list of integers from 1 to 10, you can use Enumerable. Range.

Flavor 2
Another flavor of it is used in a situation when you need to iterate something for a fixed number of times:

for(int i=1; i<=10; i++)
{
    Print("My name is printed " +  i + " times");
}

This code can be replaced with following LINQ:

var list = Enumerable.Range(1,10).Select(item => "My name is printed " + item + " times").ToList();

AWESOME, isn't it?

Flavor 3:

Printing a table of 5:

var list = Enumerable.Range(1,10).Select(item =>  Console.WriteLn( (item*5).ToString()).ToList();

Flavour 4

In the following class House, there are rooms. Sat the situation is we want to print the room number against each room for all houses. 

Here is the class structure: 


class House
{
    public string Name { get; set; }
    public int Rooms;
}

    var houses = new List<House>
    {
        new House{Name = "Condo", Rooms = 3},
        new House{Name = "Villa", Rooms = 10}
    };


In simple words, For each house, iterate to all rooms of this house and print room number.
So the algorithm is something like :

For each house in Houses
    For j = 1 to house.Rooms.Count
          print house.Name + "room numer " + j
    EndFor
EndFor

Hence the simplest form of traditional code is :


var roomsIterate = new List();
    foreach (var h in houses)
    {
        for (int i = 1; i < h.Rooms + 1; i++)
        {
            roomsIterate.Add(h.Name + " room number " + i);
        }
    }
But we can also reduce these lines of code using LINQ and Lambda:

 var roomsLinq = houses.SelectMany(h => Enumerable.Range(1, h.Rooms).Select(i => h.Name + " room number " + i));

Flavor 5:

Enumerable.Range can be used to initialize the data class in a collection. For example:

List<House> houses = new List<House>();
for(int i = 0 i<=9 ; i++)
{
  houses.Add( new House());
}


This code can be boiled in LINQ as :

List<House> houses = new List<House>(Enumerable.Range(1, 10).Select(item => new House());
      



You can think about likeEnumerable.Range a tool of retrieving a subset of a collection.


No comments: