C# Switch Case with 💻Lamda Expression
--
In C#, the switch
statement is used for conditional branching based on the value of an expression. It allows you to compare the expression against multiple possible constant values (cases) and execute the code block associated with the first matching case. The switch
statement provides a more concise way to handle multiple conditional branches compared to using a series of if-else if
statements.
Switch Case: Before Using Lambda Expressions
public static class WithoutLambdaExpressions
{
public static string GetLetterGrade(int numericalGrade)
{
string letterGrade;
switch (numericalGrade)
{
case int n when n >= 90:
letterGrade = "A";
break;
case int n when n >= 80:
letterGrade = "B";
break;
case int n when n >= 70:
letterGrade = "C";
break;
case int n when n >= 60:
letterGrade = "D";
break;
default:
letterGrade = "F";
break;
}
return letterGrade;
}
}
In this example:
- The program prompts the user to enter a numerical grade.
- It uses
int.TryParse
to convert the user's input into an integer. - The
GetLetterGrade
function takes the numerical grade as an argument and uses a switch statement to determine the corresponding letter grade. - The switch statement uses pattern matching (
case int n when n >= 90
) to specify conditions for each case. - The resulting letter grade is then displayed to the user.
This example demonstrates how to use a switch statement to perform conditional branching based on the value of a variable.
Switch Case: After Using Lambda Expressions
public static class UsingLambdaExpressions
{
public static Func<int, string> GetLetterGrade = grade => new Dictionary<int, string>
{
{ 90, "A" },
{ 80, "B" },
{ 70, "C" },
{ 60, "D" }
}.FirstOrDefault(entry => grade >= entry.Key).Value ?? "F";
}
In this code:
- We define a dictionary that maps numerical grades to letter grades.
- We use the
FirstOrDefault
method with a lambda expression to find the first entry in the dictionary where the numerical grade is greater than or equal to the key. - If no matching entry is found, it defaults to “F”.
- We define
GetLetterGrade
as a lambda expression that takes an integer argument and returns the corresponding letter grade using the dictionary andFirstOrDefault
.
This lambda expression achieves the same result as the original GetLetterGrade
method but in a more compact way using a dictionary and LINQ.
Execute Program
using SwitchCaseExm;
Console.Write("Enter your numerical grade: ");
if (int.TryParse(Console.ReadLine(), out int numericalGrade))
{
string _WithoutLambdaExpressions = WithoutLambdaExpressions.GetLetterGrade(numericalGrade);
string _UsingLambdaExpressions = UsingLambdaExpressions.GetLetterGrade(numericalGrade);
Console.WriteLine($"Your letter grade is: {_UsingLambdaExpressions}");
}
else
{
Console.WriteLine("Invalid input. Please enter a numerical grade.");
}
Output