c# - 如何在 WinForms 和 EntityFramework 中生成 Pivot Datagridview

标签 c# winforms linq

我想在 WinForms 和 EntityFramework 中生成一个 Pivot Datagridview,从这些实体开始:

public class Return
{
    public Return()
    {
        this.ReturnQty = new List<ReturnQty>();
    }

    public int Id { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
    public Nullable<int> ReturnReason { get; set; }
    public Nullable<System.DateTime> Belastungsdatum { get; set; }
    public virtual ICollection<ReturnQty> ReturnQty  { get; set; }
}

public class ReturnQty
{
    public int ID { get; set; }
    public int Return_ID { get; set; }
    public string ItemNo { get; set; }
    public Nullable<decimal> Qty { get; set; }
    public virtual Return Return { get; set; }
}

数据透视表网格应如下所示:

enter image description here

这就是我现在拥有的:

public static class ReturnReasons
{

    public static string a { get { return "Grund nicht erfasst"; } }
    public static string a1 { get { return "Artikel mangelhaft"; } }
    public static string a2 { get { return "Bestellirrtum Kunde"; } }
    public static string a3 { get { return "Doppelbestellung Kunde"; } }
    public static string a4 { get { return "AV Kunde"; } }
    public static string a5 { get { return "Kundenadresse falsch"; } }
    public static string a6 { get { return "Kunde nicht erreichbar"; } }
    public static string a7 { get { return "Kundenstorno"; } }
    public static string a8 { get { return "Nichtgefallen"; } }
    public static string a9 { get { return "Transportschaden UPS/DHL/GLS"; } }
    public static string a10 { get { return "Transportschaden Spedition"; } }
    public static string a11 { get { return "Transportschaden verdeckt"; } }
    public static string a12 { get { return "Kommissionierungsfehler"; } }
    public static string a13 { get { return "Fehler Auftragserfasung"; } }
    public static string a14 { get { return "Lieferverzögerung"; } }
    public static string a15 { get { return "Warenrücksendung lt. Vereinbarung"; } }
    public static string a16 { get { return "ohne Grund/sonstiges"; } }
}

        public class RetourenPivot
    {
        public string Item{ get; set; }
        public IEnumerable<int?> ReturnReason{ get; set; }
        public IEnumerable<decimal?> Qty{ get; set; }
    }

        private void DG_databind()
    {
        var query = _data.RepositoryRetouren.GetAll<ReturnQty>();
        // A Linq to EF which creates a List of concreate class called RetourenPivot.
        var queryResults = (from iso in query
                            orderby iso.ItemNo ascending
                            group iso by iso.ItemNo into isoGroup
                            select new RetourenPivot()
                            {
                                Item = isoGroup.Key,
                                ReturnReason = isoGroup.Select(y => y.Return.ReturnReason),
                                Qty = isoGroup.Select(v => v.Qty)
                            }).ToList();


        // Call a function to create a dynamically created data table with the needed columns

        // Create a DataTable as a DataSource for the grid
        DataTable dt = new DataTable();
        // Create the DataColumns for the data table
        DataColumn dc = new DataColumn("Artikel", typeof(string));
        dt.Columns.Add(dc);

        // Get a list of Distinct Reasons
        var ReasonLabel = (from yList in queryResults.Select(Reason => Reason.ReturnReason)
                           from Reason in yList
                           select Reason.ToString()).Distinct().ToList();

        // Create the DataColumns for the table
        ReasonLabel.ForEach(delegate(string Reason)
        {
            var reasonTexts = typeof(ReturnReasons).GetProperties().Where(p => p.Name == "a" + Reason).ToList()[0].GetValue(null, null).ToString();
            dc = new DataColumn(reasonTexts, typeof(string));
            dt.Columns.Add(dc);
        });

        // Populate the rowa of the DataTable
        foreach (RetourenPivot rec in queryResults)
        {
            // The first two columns of the row always has a ISO Code and Description
            DataRow dr = dt.NewRow();
            dr[0] = rec.Item;

            // For each record
            var Reason = rec.ReturnReason.ToList();
            var Qty = rec.Qty.ToList();

            // Because each row may have different reasons I am indexing
            // the with the string name
            for (int i = 0; i < Qty.Count; i++)
            {
                var reasonTexts = typeof(ReturnReasons).GetProperties().Where(p => p.Name == "a" + Reason[i].ToString()).ToList()[0].GetValue(null, null).ToString();
                dr[reasonTexts] = Qty[i].Value;
            }

            // Add the DataRow to the DataTable
            dt.Rows.Add(dr);
        }

        // Bind the DataTable to the DataGridView
        dataGridViewSummary1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
        dataGridViewSummary1.ColumnHeadersHeight = 200;

        //Connect Grid with DataSource
        //this.dataGridViewSummary1.AutoGenerateColumns = true;
        this.dataGridViewSummary1.DataSource = dt;
    }

问题是,queryResults 中的每个 RetourenPivot 可能有多个具有相同 ReturnReason 的数量,但我不知道如何对它们进行求和。 例如。现在看起来像

项目 123 返回原因 {0, 0, 0, 0, 1, 16} 数量 {1, 1, 2, 1, 5, 1}

这意味着,对于原因 0,有 4 个数量。它应该看起来像

项目 123 返回原因 { 0, 1, 16} 数量 {5, 5, 1}

最佳答案

这不是秘诀,只是解决您问题的一些建议。

1) ReturnReason 应该是一个类:

public class ReturnReason
{
   public int Code { get; set; }
   public string Description {get; set;}
}

2) 创建ReturnReasonList 类。将其作为单例实现并使用它提供原因:

public sealed class ReturnReasonList
{
   protected List<ReturnReason> pInstance = new List<ReturnReason> {
      { .Code=1, .Description="whatever reason 1" },
      { .Code=2, .Description="whatever reason 2" },
      ... 
      { .Code=n, .Description="whatever reason n" }};


   private ReturnReasonList() {}

   public List<Returnreason> pInstance
   {
      get
      {
         return pInstance;
      }
   }
}

3) 考虑每对产品真正需要什么(ItemNo、ReturnReason):

public class ReturnedQuantity 
{
   int ItemNumber { get; set; }
   Returnreason { get; set;}
   int Quantity {get; set;}
}

4)现在您必须根据返回数据创建一个列表:

var query = _data.RepositoryRetouren.GetAll<ReturnQty>();
List<ReturnedQuantity> returns = from r in query
                                 join rs in ReturnReasonList.Instance
                                 on r.ReturnReason = rs.Code
                                 group by rs, r.ItemNo
                                 select new ReturnedQuantity() {.ItemNo = r.ItemNo, .Reason= rs, .Quantity = SUM(r.Qty) };

5) 使用 ReturnReasonList.Items 中的项目填充 DataGridView 列集合

6) 使用文章列表中的项目填充 DataGridView 行集合。

7) 用数量填充 DataGridView 单元格。

关于c# - 如何在 WinForms 和 EntityFramework 中生成 Pivot Datagridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13080734/

相关文章:

c# - 如何强制我的 lambda 表达式提前求值?修复 lambda 表达式的怪异问题?

c# - 将查询理解转换为 LINQ 中的可枚举扩展方法

c# - Cassandra:参数类型不匹配

c# - 自托管 Web Api C# 与 Windows 窗体错误

c# - Entity Framework 中的上下文中缺少 AsNoTracking() 方法

c# - 不能定义没有 PK 的表

c# - ListView 图标未被删除。以另一种方式显示?

C# Windows 窗体倒计时器

c# - 消费者不拉卡夫卡消息

c# - Amazon S3 是否支持多文件原子上传?