"if" condition inside Select Clause of LINQ Query.

In LINQ you can't use "if" statement directly in select clause, but you can achieve this by using ternary operator.

Consider you are querying an Array of object & the object internally contains another object. We have to select some field from inner object. But it may be chance that for some cases inner object is null. So to prevent your query from throwing "Object Reference not set to instance of object exception.", you need to check for null object in select clause.

Code:

class Periods
        {
            public int StartYear;
            public int EndYear;
        }



class student
        {
            public int RollNo;
            public string name;
            public DateTime DOB;
            public Periods coursePeriod;
        }



//There is an array of student object which internally contains Periods object.

student[] arrStudents= new student[100];

// You have to fetch list of students and time period spend in college
//code to fill arrStudents Array.
//output object
class studentCousePeriod
        {
            public int Rollno;
            public int StartYear;
            public int EndYear;
        }

LINQ :



studentCousePeriod[] scp = null;
 scp = (from s in arrStudents
        select new studentCousePeriod()
         {
           Rollno = s.RollNo,
           StartYear = s.coursePeriod != null ? s.coursePeriod.StartYear : 0,
           EndYear = s.coursePeriod != null ? s.coursePeriod.EndYear : 0
         }).ToArray();





2 comments:

  1. Sega CDX 32X Console (PAL/Cd32X) (Cd32X - LSAT 1xbet korean 1xbet korean betway login betway login 8078seminole hard rock human resources - Bet

    ReplyDelete
  2. Hub Of Computer Tricks And Programming: "If" Condition Inside Select Clause Of Linq Query. >>>>> Download Now

    >>>>> Download Full

    Hub Of Computer Tricks And Programming: "If" Condition Inside Select Clause Of Linq Query. >>>>> Download LINK

    >>>>> Download Now

    Hub Of Computer Tricks And Programming: "If" Condition Inside Select Clause Of Linq Query. >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete