Abhilash JA Abhilash JA - 1 month ago 4
C# Question

LINQ - .Split(new[] { ' ' }) string and set default value if found null

Here is my LINQ query

var listLogOutItems =
(from A in data
orderby A.FirstName
select new {
Login = "Logout",
Name = A.FirstName + " " + A.SurName,
ID = A.Id,
LogoutDate = A.LogOutTime.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[0]
}).Distinct();


if A.LogOutTime is null then return "Unknown". How can do this?

Answer

The simplest way is probably to use the null coalescing operator ??.

LogoutDate = (A.LogOutTime ?? "Unknown").Split(...)[0]

If A.LogOutTime is null, it'll use "Unknown" instead. This is slightly inefficient as it will be calling Split on a string we know doesn't need splitting... in C# 6 you could use the null conditional operator instead:

LogoutDate = A.LogOutTime?.Split(...)[0] ?? "Unknown" 

Here, if A.LogOutTime is null, Split won't be evaluated, and the result of that part of the expression will be null - then the null coalescing operator is used just at the end.

As an aside, rather than creating a new char[] every time, you might as well just have a static field:

private static readonly ArrayWithSpace = new[] { ' ' };

Then reuse that on every call to Split.

Comments