Replacing Loops With LINQ
Mohammad Tarem

Replacing Loops With LINQ

I often find myself iterating through an array of items either to filter, find or do something. LINQ is so powerful and expressive. It promotes clean code and shows the intent of it in a declarative way. I resisted the idea of using it instead of the classic structures of C# language mainly because I write code in other languages and sometimes the one-to-one mapping gets difficult. 

But I finally gave up and now I’m replacing every loop with a LINQ statement. 

Here are few examples:

Looking for object with Id equals 5

var array = new Test[]
{ 
    new Test{ Id = 1, Name = "One" },
    new Test{ Id = 2, Name = "Two" },
    new Test{ Id = 3, Name = "Three" },
    new Test{ Id = 4, Name = "Four" },
    new Test{ Id = 5, Name = "Five" },
    new Test{ Id = 6, Name = "Six" },
    new Test{ Id = 7, Name = "Seven" }
};

 

// The classic way 

for(int i = 0; i < array.Length; ++i)
{
    if (array[i].Id == 5)
    {
        retrun array[i];
    }
}


// The LINQ way

array.FirstOrDefault(t => t.Id == 5);        

Finding all items with Id more that 5


// The classic way

var newArray = new List<Test>();
for(int i=0; i < array.Length; ++i)
{
    if (array[i].Id > 5)
    {
        newArray.Add(array[i]);
    }
}


// The LINQ way

array.Where(t => t.Id > 5).ToList();        

Mapping to another object


// The classic way

var newArray = new List<Test2>();
for(int i=0; i < array.Length; ++i)
{
    newArray.Add(new Test2 { Id = array[i].Id });
}



// The LINQ way

array.Select(t => new Test2 { Id = t.Id });        

Chunking the array


// The classic way

var chunked = new List<List<Test>>();
int i = 0;
while(i < array.Length)
{
    var newArray = new List<Test>();
    for(int j = 0; j < 3; ++j)
    {
        newArray.Add(array[i++]);
        if (i >= array.Length)
            break;
    }
    chunked.Add(newArray);
}


// The LINQ way

array.Chunk(3).ToArray();        

Finding Maximum / Minimum


// The classic way 

int max = 0;
int min = 0;
for(int i = 1; i < array.Length; ++i )
{
    if (array[max].Id < array[i].Id)
    {
        max = i;
    }


    if (array[min].Id > array[i].Id)
    {
        min = i;
    }
}

// return array[max] or array[max] 

// The LINQ way

array.MaxBy( t => t.Id);
array.MinBy( t => t.Id);        

Removing some of first elements


// The classic way

var newArray = new List<Test>();
for(int i = 3; i < array.Length; ++i )
{
    newArray.Add(array[i] );
}




// The LINQ way

array.Skip(3).ToList();        

Reversing elements



// The classic way 

var newArray = new List<Test>();
for(int i = array.Length - 1; i >= 0; --i )
{
    newArray.Add(array[i]);
}



// The LINQ way

array.Reverse();        

The list goes on for operations such as concatenation, union, intersection, distinction and flattening an array. The result is high quality code without the smelly indices and loops.


Happy Coding!

Cheers

Mohammad Tarem

To view or add a comment, sign in

More articles by Mohammad Tarem

Others also viewed

Explore content categories