LINQ single entry or default if no entry

I am new to LINQ, and I like it, but I'm trying to load in some forms by requesting one entry (student). If this does not exist, I want to use the default values, i.e. Empty lines false bools ...

so i used:

db = new DataClassesDataContext();        
student = db.ss_students.SingleOrDefault(p => p.student_id == studentID);
txtRegNumber.EditValue = student.car_reg_no;

This failed when assigning student.car_reg_no. I realized that it seems that I misunderstood the SingleOrDefault method, and it actually returns null for the student if he cannot find the record. For some reason I thought that it would return the default values ​​for each of the fields, such as student.car_reg_no. I think I still think in database mode.

This is not a problem, I can make code like this:

db = new DataClassesDataContext();        
student = db.ss_students.SingleOrDefault(p => p.student_id == studentID);
if (student != null) 
{
        txtRegNumber.Text = student.car_reg_no;
        //assign more control values
}

And the default values ​​can be assigned to controls in another or assigned directly to the form.

, - ?

, , . .

, , . bools .

+3
1

SingleOrDefault .

  • null //
  • 0/false
    • Nullable<T>, null

null - , , " ?". ... :

YourType x = query.SingleOrDefault() ?? new YourType();

" " (new ...), NULL. :

YourType x = query.SingleOrDefault();
if(x==null) { // use a default
    x = new YourType();
}
+9

Source: https://habr.com/ru/post/1713742/


All Articles