patterncsharpModerate
Setting output parameter inside LINQ select
Viewed 0 times
linqoutputsettingselectparameterinside
Problem
Is there a way to reduce the number of lines by setting the output variable inside LINQ select statement? How would you do it?
public void GetSomeValue(int bonusID, out decimal? maxGiving, out int? isActive)
{
maxGiving = 0;
isActive = 0;
try
{
var con = new BonusModelDataContext();
var a = con.Bonus
.Where(c => c.ID == bonusID)
.Select(c => new { maxGiving = c.maxGiving, isActive = c.isActive })
.SingleOrDefault();
maxGiving = a.maxGiving;
isActive = a.isActive;
// return iovation;
}
catch(Exception ex)
{
//return -1;
}
}Solution
No, you can't do that, you can't use
But even if you could, I don't think it would be a good idea to do so, because it would make the code less readable.
There are also some suspicious practices in your code:
out parameters in a lambda.But even if you could, I don't think it would be a good idea to do so, because it would make the code less readable.
There are also some suspicious practices in your code:
- You're using
SingleOrDefault(), but you don't check the result fornull. If you don't want to check fornull, useSingle()which will throw an exception if the query returns an empty collection.
- You're catching all exceptions. You should catch only the exceptions you know about. And you certainly shouldn't use something like
return -1, it's much better to just let the exception bubble up and catch it somewhere up the call stack. Another option might be catching the exception, wrapping it in some more specific exception and throwing that.
- Why are you setting the output parameters to
0by default? They are nullable, so setting them tonullmakes more sense to me.
Context
StackExchange Code Review Q#11328, answer score: 11
Revisions (0)
No revisions yet.