Switch Case in LINQ

Let us see how to derive conditional results using LINQ. This is a typical example of a switch case statement in LINQ.

In this example, we will print "Pass", "Fail" and "On Hold" depending on the 'Result' of the student. We are using a switch case pattern to determine the string. If the Result is 'P' we print 'Pass'; if the Result is 'F' we print 'Fail' else we print 'On Hold' if it is neither 'P' or 'F'.

C#


List<Student> stuList = new List<Student>();


stuList.Add(new Student() { ID = 1, FName = "Shakiy",Result = 'P' });


stuList.Add(new Student() { ID = 2, FName = "Mary", Result = 'P' });


stuList.Add(new Student() { ID = 3, FName = "Bill", Result = 'F' });


stuList.Add(new Student() { ID = 4, FName = "Samantha", Result = 'F' });


stuList.Add(new Student() { ID = 5, FName = "Mary", Result = 'P' });


stuList.Add(new Student() { ID = 6, FName = "John", Result = 'O' });


 


var slist = from stu in stuList


             select new { Name = stu.FName, Result = stu.Result  == 'P' ? "Pass" :


                 stu.Result == 'F' ? "Fail" : "On Hold" };


 


foreach (var list in slist)


{


    // print name and result


}




VB.NET


        Dim stuList As New List(Of Student)()


        stuList.Add(New Student() With {.ID = 1, .FName = "Shakiy", .Result = "P"c})


        stuList.Add(New Student() With {.ID = 2, .FName = "Mary", .Result = "P"c})


        stuList.Add(New Student() With {.ID = 3, .FName = "Bill", .Result = "F"c})


        stuList.Add(New Student() With {.ID = 4, .FName = "Samantha", .Result = "F"c})


        stuList.Add(New Student() With {.ID = 5, .FName = "Mary", .Result = "P"c})


        stuList.Add(New Student() With {.ID = 6, .FName = "John", .Result = "O"c})


 


        Dim slist = _


         From stu In stuList _


         Select New With {Key .Name = stu.FName, Key .Result = If(stu.Result = "P"c, "Pass", If(stu.Result = "F"c, "Fail", "On Hold"))}


 


        For Each list In slist


            ' print name and result


        Next list


2 comments: