I have the following code line:
Project = x.Project == null ? null : new Model { ... }
Is there any way, in C# 6, to make this code shorter?
I have a been looking at a few ? examples but for this case I can't find a shorter solution ...
As-is your code is as short as it possibly can be. However if the class Project
is based on had a public Model ToModel(...) { }
method you could do
Project = x.Project?.ToModel(...);
UPDATE: As JonSkeet just mentioned, you could also make .ToModel(
a extension method.
public static class ExtensionMethods
{
public static Model ToModel(this Project p, ...)
{
return new Model { ... };
}
}
The syntax would still be
Project = x.Project?.ToModel(...);
No, Its as short as you can make it.
However based on this code you should actually have an if condition above it to check the value of x
if(x != null)
Project = x.Project == null ? null : new Model { ... }
else
Project = null;
You can change this to :
Project = x?.Project == null ? null : new Model { ... }
Not shorter, but an alternative solution using Linq:
Model m = new Project[] { x.Project }
.Where(p => p != null)
.Select(p => new Model { ... })
.FirstOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With