Linqify your code.


I’m sure most programmers are familiar with Linq, and agree with me that it’s great. I personally really enjoying using Linq, mostly in the form o f Linq to SQL and Linq to Objects. It also helps with simplifying your code and makes it easier to read. Some of the most useful Linq functions I find are FirstOrDefault, Any, All and Where. However sometimes I still come across developers writing loops to do work when Linq can be utilized to simplify it. So here are some simple code samples on how to use Linq to eliminate writing foreach loops.

Example 1: simple loop through strings to print to console

public void PrintStrings(IEnumerable inputs)
{
    foreach (var input in inputs)
    {
        Console.WriteLine(input);
    }
}

public void PrintStringsLinq(IEnumerable inputs)
{
    inputs.ToList().ForEach(Console.WriteLine);
}

Example 2: Only print string if condition is matched

public void PrintStrings(IEnumerable inputs)
{
    foreach (var input in inputs)
    {
        if (input.Contains("some string"))
        {
            Console.WriteLine(input);
        }
    }
}

public void PrintStringsLinq(IEnumerable inputs)
{
   inputs.Where(input=>input.Contains("some string")).ToList().ForEach(Console.WriteLine);
}

Example 3: Break printing loop if a condition is met

public void PrintStrings(IEnumerable inputs)
{
    foreach (var input in inputs)
    {
        if (!input.Contains("some string"))
        {
            break;
        }
        Console.WriteLine(input);
    }
}

public void PrintStringsLinq(IEnumerable inputs)
{
    inputs.TakeWhile(input => input.Contains("some string")).ToList().ForEach(Console.WriteLine);
}

Example 4: Make a list of strings comma separated

public void PrintStrings(IEnumerable inputs)
{
    var inputList = inputs.ToList();
    var output = string.Empty;
    for (var index = 0; index < inputList.Count; index++)
    {
        if (index == 0)
            output = inputList[index];
        else
            output = string.Format("{0},{1}", output, inputList[index]);
    }
    Console.WriteLine(output);
}

public void PrintStringsLinq(IEnumerable inputs)
{
    var output = inputs.Aggregate((first, second) => string.Format("{0},{1}", first, second));
    Console.WriteLine(output);
}

Example 5: Converting list of strings to XElements

public IEnumerable GetXElements(IEnumerable inputs)
{
    var xElements = new List();
    foreach (var input in inputs)
    {
        xElements.Add(new XElement(new XElement(input)));
    }
    return xElements;
}

public IEnumerable GetXElementsLinq(IEnumerable inputs)
{
    return inputs.Select(input => new XElement(input));
}

Example 6: Printing list of objects within a list of objects

public class Fruit
{
    public string Name { get; set; }
}

public class Basket
{
    public IEnumerable Fruits { get; set; }
}

public void PrintFruits(IEnumerable baskets)
{
    foreach (var basket in baskets)
    {
        foreach (var fruit in basket.Fruits)
        {
            Console.WriteLine(fruit.Name);
        }
    }
}

public void PrintFruitsLinq(IEnumerable baskets)
{
    baskets.SelectMany(x=>x.Fruits).ToList().ForEach(fruit => Console.WriteLine(fruit.Name));
}

Linq is capable of much more than the examples above but I find these are the common usages in my day to day coding. I do hope you will explore Linq more and unravel the power within in your code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: