patterncsharpMinor
Rewrite from .. where .. select to more compact one
Viewed 0 times
wheremorerewriteoneselectfromcompact
Problem
This is the code:
My refactorings objectives:
-
make it compact
-
check if
situation
public DateTime GibSomeStartDate(IEnumerable partnerNumbers, DateTime startTime)
{
return (from contract in this.databaseContext.Contract
where partnerNumbers.Contains(contract.Pnr) && contract.SomeDateTime >= startTime
select contract.SomeDateTime).Min();
}databaseContext Instance is child of Entity Framework DbContextMy refactorings objectives:
-
make it compact
-
check if
from where select finds nothing. In thissituation
Min() will cause an ExcetionSolution
This can be accomplished with a slight modification to your method signature and an extension method:
Here, the signature now can return
This extension method will trap
Here, the signature now can return
null if there are no records selected:public DateTime? GibSomeStartDate(IEnumerable partnerNumbers, DateTime startTime)
{
return (from contract in this.databaseContext.Contract
where partnerNumbers.Contains(contract.Pnr) && contract.SomeDateTime >= startTime
select contract.SomeDateTime).SafeMin(someDateTime => (DateTime?)someDateTime);
}This extension method will trap
Min's exception and return null instead:public static U? SafeMin(this IEnumerable source, Func selector) where U : struct
{
try
{
return source.Min(selector);
}
catch
{
return null;
}
}Code Snippets
public DateTime? GibSomeStartDate(IEnumerable<int> partnerNumbers, DateTime startTime)
{
return (from contract in this.databaseContext.Contract
where partnerNumbers.Contains(contract.Pnr) && contract.SomeDateTime >= startTime
select contract.SomeDateTime).SafeMin(someDateTime => (DateTime?)someDateTime);
}public static U? SafeMin<T, U>(this IEnumerable<T> source, Func<T, U?> selector) where U : struct
{
try
{
return source.Min(selector);
}
catch
{
return null;
}
}Context
StackExchange Code Review Q#23736, answer score: 5
Revisions (0)
No revisions yet.