How to check for nulls in a deep lambda expression?
You can't do that in a concise way. You can either make the lambda multiple lines, or use nested ternary operators:
var result = GetValue(one, x => x.Two == null ? null :
x.Two.Three == null ? null :
x.Two.Three.Four == null ? null :
x.Two.Three.Four.Foo;
Ugly, I know.
Clean way to check for Null in Lambda Expressions
var result = Store.FirstOrDefault(x => x.Products.Coupon != null && x.Products.Coupon.Any() && x.Products.Coupon[0] == 100);
Null value in lambda WHERE clause
Try to use Null-Conditional Operator ?.
introduced in C# 6.
In your example it would be
a.InstallationDateType?.ToString().ToUpper().Equals(Constants.InstallationDateTypeDish)
Deep null checking, is there a better way?
We have considered adding a new operation "?." to the language that has the semantics you want. (And it has been added now; see below.) That is, you'd say
cake?.frosting?.berries?.loader
and the compiler would generate all the short-circuiting checks for you.
It didn't make the bar for C# 4. Perhaps for a hypothetical future version of the language.
Update (2014):
The ?.
operator is now planned for the next Roslyn compiler release. Note that there is still some debate over the exact syntactic and semantic analysis of the operator.
Update (July 2015): Visual Studio 2015 has been released and ships with a C# compiler that supports the null-conditional operators ?.
and ?[]
.
What is proper way to write this linq lambda expression and deal with nulls?
Simply
double currentPopulation = detailmetrics
.Where(dm => dm.MetricScopeID == 2 && dm.MetricTypeID == 1 && dm.Timeframe.Equals("C"))
.Select(a => Convert.ToDouble(a.MetricValue))
.FirstOrDefault();
How do I check my lambda expression for null?
Firstly you can select decimal values from the objects which met the condition. And then use .DefaultIfEmpty()
method before the .Sum()
method:
runTime = db.Records
.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x)
.Select(c => c.RunMinutes)
.DefaultIfEmpty()
.Sum();
DefaultIfEmpty()
function inserts a single element with a default value if the sequence is empty. And as we know, defualt value for decimal
type is 0.0M
.
(Default Values Table)
Additionally:
You didn't tell us Linq to What? are you using. But, if you are using LinqToEntity, then you must change your code as (DefaultIfEmpty
is not supported by EF):
runTime = db.Records
.Where(c => c.MachineDesc.Contains(strMachine) && c.ProductionDate == dt && c.Shift == x)
.Sum(c => (decimal?)c.RunMinutes) ?? 0;
How to check multiple objects for nullity?
EDIT 2018: As of Apache Commons lang 3.5, there has been ObjectUtils.allNotNull()
and ObjectUtils.anyNotNull()
.
No.
None of Apache Commons Lang (3.4), Google Guava (18) and Spring (4.1.7) provide such a utility method.
You'll need to write it on your own if you really, really need it. In modern Java code, I'd probably consider need for such a construct a code smell, though.
lambda check for null and then set to 0
This expression makes no sense (and doesn't compile):
x => x.ExchangeAttempts.HasValue
? x.ExchangeAttempts.Value
: 1 <= 1
That is the exact equivalent (assuming that ExchangeAttempts
is an int?
of:
int lambda( x MyClass )
{
int result;
if ( x.ExchangeAttempts.HasValue )
{
result = x.ExchangeAttempts.Value ;
}
else
{
result = 1 <= 1 ;
}
return result;
}
It fails to compile because the expression 1 <= 1
evaluates to true
.
If what you want to do is assign a default value of 1
if ExchangeAttempts
is null
, just say:
x => (x.ExchangeAttempts ?? 1) <= 1
It's shorter and more concise, and better expresses your intent.
Or, better yet:
x => x.ExchangeAttempts == null || x.ExchangeAttempts <= 1
Logical expressions short circuit, so the alternative is only ever tried if the first test fails, so the above returns true
when either
x.ExchangeAttempts
has no value, orx.ExchangeAttempts
has a value less than or equal to 1
And returns false
when
x.ExchangeAttempts
has a value and that value is > 1.
Related Topics
How to Implement "Access-Control-Allow-Origin" Header in ASP.NET
Wpf How to Access Control from Datatemplate
How to Secure Passwords Stored Inside Web.Config
C# ASP.NET Write File to Client
Hide Form Instead of Closing When Close Button Clicked
Why Is Parallel.Foreach Much Faster Then Asparallel().Forall() Even Though Msdn Suggests Otherwise
C#: Getting Size of a Value-Type Variable at Runtime
Different Forms of the Wcf Service Contract Interface
Difference Between the Keydown Event, Keypress Event and Keyup Event in Visual Studio
Why Doesn't the Xmlserializer Need the Type to Be Marked [Serializable]
Entity Framework with Xml Files
How to Intercept Console Output
Automatically Rename a File If It Already Exists in Windows Way