HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Rewrite from .. where .. select to more compact one

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wheremorerewriteoneselectfromcompact

Problem

This is the code:

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 DbContext

My refactorings objectives:

-
make it compact

-
check if from where select finds nothing. In this

situation Min() will cause an Excetion

Solution

This can be accomplished with a slight modification to your method signature and an extension method:

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.