The practice of materializing queries if the result is zero

From my application, I have codes like this:

student entry = (from stud in emp.students where stud.id == st.id select stud).First();

But if it is null, then my application will fail.

My current methods currently wrap them in try block, so it won't break down like:

try
{
next = emp.calendar.Where(x => x.term == "first" && x.schoolyear == year).First();
}
catch (Exception e)
{

}

or do something like this:

IEnumerable<calendar> cld = null;
//do stuff

cld = (from cd in emp.calendar where cd.regenroll >= nw && nw <= cd.regend select cd);
int count = cld.Count();

if (cls > 0)

//materialise

}

What are the best methods to check if it is null or not before processing? assuming it may or may not return a string.

+4
source share
4 answers

Use FirstOrDefault()instead First()., it will protect against a null exception.

+1
source

Try

next = emp.calendar.Where(x => x.term == "first" && x.schoolyear == year).FirstOrDefault();

, First(), , . , , . FirstOrDefault(), , , . null, .

+1

. FirstOrDefault() .First()

student entry = (from stud in emp.students 
                 where stud.id == st.id 
                 select stud
                ).FirstOrDefault();

if (entry == null)
   ...
+1

. DefaultIfEmpty() .

emp.calendar.Where(x => x.term == "first" && x.schoolyear == year).DefaultIfEmpty(/*optional default here*/).First();

( MSDN):

class Pet
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }

        public static void DefaultIfEmptyEx1()
        {
            List<Pet> pets =
                new List<Pet>{ new Pet { Name="Barley", Age=8 },
                               new Pet { Name="Boots", Age=4 },
                               new Pet { Name="Whiskers", Age=1 } };

            foreach (Pet pet in pets.DefaultIfEmpty())
            {
                Console.WriteLine(pet.Name);
            }
        }

( MSDN):

class Pet
            {
                public string Name { get; set; }
                public int Age { get; set; }
            }

            public static void DefaultIfEmptyEx2()
            {
                Pet defaultPet = new Pet { Name = "Default Pet", Age = 0 };


                List<Pet> pets1 =
                    new List<Pet>{ new Pet { Name="Barley", Age=8 },
                                   new Pet { Name="Boots", Age=4 },
                                   new Pet { Name="Whiskers", Age=1 } };

                foreach (Pet pet in pets1.DefaultIfEmpty(defaultPet))
                {
                    Console.WriteLine("Name: {0}", pet.Name);
                }

                List<Pet> pets2 = new List<Pet>();

                foreach (Pet pet in pets2.DefaultIfEmpty(defaultPet))
                {
                    Console.WriteLine("\nName: {0}", pet.Name);
                }
            }
+1

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


All Articles