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's null
then my application will crash.
My current methods as of now is to enclose them with a try block
so it won't crash 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 good practices on checking if it's null or not before processing? assuming that it may or may not return a row.
答案 0 :(得分:1)
Use FirstOrDefault()
instead of First().
it will guard against the null exception.
答案 1 :(得分:1)
Try
next = emp.calendar.Where(x => x.term == "first" && x.schoolyear == year).FirstOrDefault();
Note that you need to use First() when you know that the sequence has minimum one element. You will get an exception like you are getting when there are no elements present. And you need to use FirstOrDefault() when you have to check if the element exists like in your case. It will either return null or the default value.
答案 2 :(得分:1)
Use .FirstOrDefault() instead of .First()
student entry = (from stud in emp.students
where stud.id == st.id
select stud
).FirstOrDefault();
if (entry == null)
...
答案 3 :(得分: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);
}
}