Home
Options

How to add HasValue to LinqPad7?

Hi,
I am trying to run a Linq statement but getting this error below.
Cannot execute text selection: CS1061 'DateTime' does not contain a definition for 'HasValue' and no accessible extension method 'HasValue' accepting a first argument of type 'DateTime' could be found (press F4 to add an assembly reference or import a namespace)
How can I fix it?
Here is my sample query;
var allMonths = Enumerable.Range(1, 12).Select(i => DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(i));
var allCurrencies = OrdersDetails.Select(x => x.Currency).Distinct();

var orders = OrdersDetails
.Where(x => x.Order.OrderDateTime.HasValue && x.Order.OrderDateTime.Value.Year == 2023 && x.Status == "Completed")
.GroupBy(x => new { Month = x.Orders.OrderDateTime.Value.Month, Currency = x.Currency })
.Select(u => new
{
Month = u.Key.Month,
Currency = u.Key.Currency,
TotalSalesWithCurrency = u.Sum(x => x.TotalSellPrice)
});

var result = allMonths.SelectMany(month => allCurrencies,
(month, currency) => new { Month = month, Currency = currency })
.GroupJoin(
orders,
all => new { Month = DateTime.ParseExact(all.Month, "MMM", CultureInfo.CurrentCulture).Month, all.Currency },
order => new { order.Month, order.Currency },
(all, orderGroup) => orderGroup
.Select(order => new ReportSalesWithCurrencyDto { Month = all.Month, Currency = all.Currency, TotalSalesWithCurrency = order.TotalSalesWithCurrency })
.DefaultIfEmpty(new ReportSalesWithCurrencyDto { Month = all.Month, Currency = all.Currency, TotalSalesWithCurrency = 0 }))
.SelectMany(group => group)
.OrderBy(u => DateTime.ParseExact(u.Month, "MMM", CultureInfo.CurrentCulture).Month);
result.Dump();

public class ReportSalesWithCurrencyDto
{
public string Month { get; set; }
public string Status { get; set; }
public string Currency { get; set; }
public double? TotalSalesWithCurrency { get; set; }
}

Comments

  • Options
    edited February 8

    HasValue only works on Nullable<> values. Based on your code, I can infer OrderDateTime is returned as DateTime and not Nullable<DateTime> (or DateTime?). If this is correct, you don't need to check if it has a value. It's a value type and will have something in it even if it's default(DateTime).

Sign In or Register to comment.