The below code will show the way to use Switch Statement and Ternary operator with Statement Lambda using C#
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 =>
{
switch(i.Age < 18 ? 0:1) // note the way the ternarry 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;
}
});
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; }
}
}