Conditional Statement(s) Inside Lambda in conjunction with String Interpolation of C# 6.0

Rajnilari2015
Posted by in C# category on for Beginner level | Points: 250 | Views : 1780 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article, we will look at handling conditional statement(s) inside LINQ lambda expression in conjunction with string interpolation of C# 6.0. We will also see its usage with some specific examples.


 Download source code for Conditional Statement(s) Inside Lambda in conjunction with String Interpolation of C# 6.0

Introduction

A conditional statement in a programming language is a statement that handles a condition. e.g. IF..Else , Switch, Ternary Operators are examples of Conditional Statements. If we need to issue command for storing the results of computation for multi statements, we can use Statement Lambda. In this article , we will look into the usage of Statement Lambda with some specific examples and also will demonstrate the usage of String Interpolation feature of C#6.0 in the context.

Case 1: Use of IF..Else construct inside Lambda Expression using Statement Lambda

Consider the below program where we are using the Statement Lambda to evaluate if a person is eligible to cast vote.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var personData = new List<PersonMaster>();

            //populating some data
            Enumerable
                .Range(1, 10)
                .ToList()
                .ForEach(
                            i =>
                            personData.Add(new PersonMaster
                            {
                                PersonID = i,
                                PersonName = string.Concat("Person ", i),
                                Age = 14+i
                            })
                        );

            //Use of Statement Lambda
            var eligiblePersonData = new List<EligiblePerson>();

            personData
                .ToList()
                .ForEach(i =>
                {
                    if (i.Age < 18)
                        Console.WriteLine("Mr. {0} is not eligible to case vote as his age is {1} which is under 18",i.PersonName,i.Age);
                    else
                        eligiblePersonData.Add(new EligiblePerson
                        {
                            PersonID = i.PersonID,
                            PersonName = i.PersonName,
                            Age = i.Age
                        });
                  });

            Console.ReadKey();
        }
    }

    //The main person model
    public class PersonMaster
    {
        public int PersonID { get; set; }
        public string PersonName { get; set; }
        public int Age { get; set; }

    }

    //Eligible Person Model
    public class EligiblePerson
    {
        public int PersonID { get; set; }
        public string PersonName { get; set; }
        public int Age { get; set; }
    }   
}

As can be figure out from the below image

The statement expression blocks started inside the Foreach Extension Method. Inside that, we have written our conditional statement by using the IF..Else constructs, where inside the IF block we are displaying those records into the console which does not satisfy the requirements of casting votes and inside the ELSE block we made a Collection with those records, that does satisfy the requirement.

Case 2: Use of Switch Statement and Ternary operator inside Lambda Expression using Statement Lambda

The above program is re-written in a little different way using Switch Statement and Ternary operator as demonstrated below

personData
        .ToList()
        .ForEach(i =>
        {

           switch(i.Age < 18 ? 0:1) // note the way the ternary operator is used inside the switch statement as an expression
            {
                case 0:
                    Console.WriteLine("Mr. {0} is not eligible to case vote as his age is {1} which is under 18", i.PersonName, i.Age);
                    break;
                case 1:
                    eligiblePersonData.Add(new EligiblePerson
                    {
                        PersonID = i.PersonID,
                        PersonName = i.PersonName,
                        Age = i.Age
                    });
                    break;
            }
        });

The code snippet is same as we have seen with the case of IF..ELSE construct except the ternary operator is used inside the switch statement as an expression for the purpose of evaluation

The use of String Interpolation of C# 6.0

Let us re-write the above code snippet in the String Interpolation of C# 6.0 way

switch (i.Age < 18 ? 0 : 1)
{
    case 0:

       //note the usage of String Interpolation - a feature of C# 6.0 

        string toDisplay = $"Mr. {i.PersonName}   is not eligible to case vote as his age is {i.Age}  which is under 18";
        Console.WriteLine(toDisplay); 
        break;
    case 1:
        eligiblePersonData.Add(new EligiblePerson
        {
            PersonID = i.PersonID,
            PersonName = i.PersonName,
            Age = i.Age
        });
        break;
}

C# 6.0 comes with a unique feature where the String Interpolation happens in between the strings.Rather than placing the positional placeholders in the old ways, we can use the real values like the way we have used the real properties inside the string braces e.g. {i.PersonName} and {i.Age}.

In this case, the string needs to begin with a $ sign indicating a new kind of string interpolation to happen. At run time, {i.PersonName} will be replaced with the value of the properties.

Let us observe, what the IL says about the String Interpolation

So, the IL reveals that after compilation, the actual statement(s) are a call to string.Format.So String Interpolation is a trick made by the compiler to invoke the string.Format function.

Running all the above examples will yield the below

Reference

Lambda Expressions (C# Programming Guide)
Interpolated Strings

Conclusion

In this article we have seen the usage of Statement Lambda with Conditional Statement(s) by providing sufficient examples to understand the same.Also we have provided a demonstration of the use of the String Interpolation feature of C# 6.0 in that context. Hope this will be helpful.Thanks for reading. Zipped file attached.

N.B.~The solution was built using VS2015.

Recommendation
Read CRUD with NodeJS and ExpressJS after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Posted by: Sheonarayan on: 12/4/2015 | Points: 25
Nice article Rajnilari2015.

Thanks for sharing.
Posted by: Rajnilari2015 on: 12/4/2015 | Points: 25
Thanks you Sir.
Posted by: Poster on: 12/4/2015 | Points: 25
Hell lot of things to learn from this posts, it's amazing to see that even conditional statements are possible in the LINQ Lamda expressions.

Thanks Rajnilari.
Posted by: Rajnilari2015 on: 12/4/2015 | Points: 25
Thanks a lot for the motivational words.
Posted by: Rajayadav on: 12/7/2015 | Points: 25
Good job, Thanks for sharing..

Posted by: Rajnilari2015 on: 12/7/2015 | Points: 25
Thanks a lot
Posted by: Ermahesh2009 on: 12/12/2015 | Points: 25
Hi Rajnilari

Great help it help to me the exact concept .

code for implement android search .



lstNames.ForEach(Function(str)
For Each CheckValue In _formerValue.ToUpper().Split(stringSeparators, StringSplitOptions.None)
If str.ToUpper().Split(stringSeparators, StringSplitOptions.None).Any(Function(i) i.StartsWith(CheckValue)) Then
IsAllWordsMatchInString = True
Else
IsAllWordsMatchInString = False
Exit For
End If
Next
If IsAllWordsMatchInString Then
If Not IsSomethingMatch Then
ShowListBox()
IsSomethingMatch = True
End If
_listBox.Items.Add(str)
End If
End Function)


Posted by: Rajnilari2015 on: 12/12/2015 | Points: 25
@Ermahesh2009, glad to know that.
Posted by: Rajnilari2015 on: 12/16/2015 | Points: 25
@Rajayadav, thanks a lot

Login to post response

Comment using Facebook(Author doesn't get notification)