填充类时如何在LINQ中创建字典? [英] How to create a dictionary in LINQ when populating a class?

查看:69
本文介绍了填充类时如何在LINQ中创建字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明:

目前,我有一个看起来像这样的课程:

At the moment I have a class which looks like so:

 public class SupplierSummaryReport {
            public string SupplierName { get; set; }
            public Dictionary<string, decimal> DateValues { get; set; }
        }

使用LINQ,我正在尝试创建SupplierSummaryReport类的IQueryable列表.但是,当尝试使用C#创建字典时,应用程序将失败.我不确定如何创建字典,有人可以帮忙吗?

Using LINQ, I am trying to create an IQueryable list of the SupplierSummaryReport class. However, when trying to create the dictionary in C#, the application fails. I'm not sure how to create the dictionary, can anyone help?

LINQ/C#:

 public IQueryable<APData.Audit.Models.ReportModels.SupplierSummaryReport> GetSupplierSummaryReportData() {
            var data = (from i in _ctx.Invoices
                        where i.Turnover == true
                        select new {
                            Year = i.InvoiceDate.Year.ToString(),
                            AccountName = i.AccountName,
                            Value = i.NetAmount_Home ?? 0
                        });

            return data.GroupBy(r => new { r.Year, r.AccountName })
                .Select(g => new APData.Audit.Models.ReportModels.SupplierSummaryReport {
                    SupplierName = g.Key.AccountName,
                    //I believe it fails when creating the dictionary
                    DateValues = new Dictionary<string, decimal> {
                        {g.Key.Year, g.Sum(r=> r.Value)}
                    }
                }).OrderBy(r => r.SupplierName);
        }

预期结果:

Supplier Name = "Test", DateValues = {2010, 500}
Supplier Name = "Test2", DateValues = {2011, 900}

实际结果:

收到此错误:

仅支持具有单个元素的列表初始值设定项 LINQ到实体.

Only list initializer items with a single element are supported in LINQ to Entities.

推荐答案

一旦启动.Select(g =>,就没有必要创建字典了,因为只有一个g.Key.如果您尝试创建一个只有一个元素的字典.我认为您的逻辑有误.

Once you start the .Select(g => there's no point creating a dictionary as you have only one g.Key. You would only be creating a dictionary with one element in it if you tried. I think you have your logic wrong.

我认为这是您的return语句的样子:

I think this is what your return statement should look like:

return
    data
        .GroupBy(r => r.AccountName)
        .Select(g => new APData.Audit.Models.ReportModels.SupplierSummaryReport
        {
            SupplierName = g.Key.AccountName,
            //I believe it fails when creating the dictionary
            DateValues = g
                .GroupBy(x => x.Year, x => x.Value)
                .ToDictionary(x => x.Key, x => x.Sum())
        })
        .OrderBy(r => r.SupplierName);

现在,您可能需要在data之后放置一个.ToArray(),以将记录放入内存中,以使此查询正常工作.

Now you may need to put a .ToArray() after data to bring the records in to memory to make this query work.

这篇关于填充类时如何在LINQ中创建字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆