Linq - pulling a value from the result of a null query

I have a linq query that should output a date column from a string. The expression currently looks like this

myObject.OrderByDescending(s=> s.MyDate).Where(s => s.CRAStatus.Description == "CheckedOut").FirstOrDefault().MyDate) 

The problem is that if there are no lines that are "CheckedOut", the request will return null and trying to get "MyDate" will throw an exception. We have several detailed solutions, such as:

 .ForMember(dest => dest.CheckOutDate, opt => opt.MapFrom(src => { var temp = src.CRAStatusChangeEvents.OrderByDescending(s=> s.MyDate).Where(s => s.CRAStatus.Description == "CheckedOut").FirstOrDefault(); return temp == null ? temp.MyDate : null; })); 

But it would be nice to find something more concise. Any ideas?

+4
source share
4 answers

Why not

 myObject.OrderByDescending(s=> s.MyDate) .Where(s => s.CRAStatus.Description == "CheckedOut") .Select(s => s.MyDate as DateTime?) .FirstOrDefault(); 

or

 myObject.Where(s => s.CRAStatus.Description == "CheckedOut") .Max(s => s.MyDate as DateTime?); 
+4
source

One option is to set default, if empty , to an "empty" instance (think of string.Empty - its known instance, which is an empty result):

 var date = (myObject .OrderByDescending(s=> s.MyDate) .Where(s => s.CRAStatus.Description == "CheckedOut") .DefaultIfEmpty(MyObject.Empty) .FirstOrDefault()).MyDate; 

Here is a snippet that shows how it works:

 var strings = new string[]{"one", "two"}; var length = (strings.Where(s=>s.Length > 5) .DefaultIfEmpty(string.Empty) .FirstOrDefault()).Length; 

run this and length is 0. Delete the line DefaultIfEmpty and get NRE.

+3
source
 var checkedOut = myObject.Where(s => s.CRAStatus.Description == "CheckedOut"); if (checkedOut.Count() > 0) { var result = checkedOut.Max(s=> s.MyDate).MyDate; } 
+1
source

What about the extension method?

 static class MyObjectEnumerableExtensions { public static TMember GetMemberOfFirstOrDefault<TMember>(this IEnumerable<MyObject> items, Func<MyObject, TMember> getMember) { MyObject first = items.FirstOrDefault(); if (first != null) { return getMember(first); } else { return default(TMember); } } } 

Sample Usage:

 List<MyObject> objects = new List<MyObject>(); objects.Add(new MyObject { MyDate = DateTime.MinValue }); var filteredObjects = from s in objects where s.MyDate > DateTime.MinValue select s; DateTime date = filteredObjects.GetMemberOfFirstOrDefault(s => s.MyDate); Console.WriteLine(date); 
+1
source

All Articles