简体   繁体   中英

How to create a dictionary where key is a day and value is a list of object

I have the following object:

public class ExchangeRate
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [Min(0)]
    public double Value { get; set; }

    [Required]
    public DateTime ValidFrom { get; set; } = DateTime.Now;

    [MaxLength(3)]
    [Required]
    public int CurrencyId { get; set; }
    public virtual CurrencyDto Currency { get; set; }
}

I need to create a dictionary from list of ExchangeRate type, where the key is the day property from ValidFrom, and the value in the dictionary is a list of Exchange objects where the ValidFrom propery day attribute is equal to the key.

This is what I tried:

var exchangeRates = dbContext.ExchangeRates.Where(x => x.ValidFrom.Year == DateTime.Now.Year)
                                           .Where(x => x.ValidFrom.Month == DateTime.Now.Month)
                                           .Where(x => x.ValidFrom.Day >= day)
                                           .GroupBy(k => k.ValidFrom.Day, v => v)
                                           .ToDictionary(x => x.Key, x => x.ToList());

I got the following error:

System.InvalidOperationException : The LINQ expression 'DbSet() .Where(x => x.ValidFrom.Year == DateTime.Now.Year) .Where(x => x.ValidFrom.Month == DateTime.Now.Month) .Where(x => x.ValidFrom.Day >= __day_0) .GroupBy( keySelector: k => k.ValidFrom.Day, elementSelector: v => v)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'.

thnx

This is how I solved at the end:

        var exchangeRates = await dbContext.ExchangeRates.Where(x => x.ValidFrom.Year == DateTime.Now.Year)
                                                         .Where(x => x.ValidFrom.Month == DateTime.Now.Month)
                                                         .Where(x => x.ValidFrom.Day >= day)
                                                         .GroupBy(k => k.ValidFrom.Day, v => v)
                                                         .Select(x => new KeyValuePair<int, List<ExchangeRateDto>>(x.Key, x.ToList()))
                                                         .ToDictionaryAsync(x => x.Key, x => x.Value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM