locked
Error when to create column RRS feed

  • Question

  • User-373571997 posted

    try
    {
    var query = (from b in base.MyEntities.shipmentsamples
    group b by b.color into bGroup
    select new { color = bGroup.Key, Data = bGroup, Total = bGroup.Sum(z => z.qty) });

    var grandTotal = base.MyEntities.shipmentsamples.Sum(d => d.qty);
    result = new DataTable();

    foreach (var itm in query.ToList())
    {
    var sizeTotal = itm.Data.Sum(c => c.qty);
    foreach (var itm2 in itm.Data)
    {
    result.Columns.Add("ID", typeof(Int32));
    result.Columns.Add("Color", typeof(Int32));
    result.Columns.Add(itm2.size.ToString(), typeof(Int32));
    }
    }
    
    
    guy this is my coding , i want to ask  how i can avoid when i looping ?
    Tuesday, October 11, 2011 11:53 PM

Answers

  • User3866881 posted

    Hello:)

    According to my experience, I think there's something wrong with your logic——

    foreach (var itm2 in itm.Data)
    {
    result.Columns.Add("ID", typeof(Int32));
    result.Columns.Add("Color", typeof(Int32));
    result.Columns.Add(itm2.size.ToString(), typeof(Int32));
    }

    If you write foreach there, I'm afraid you'll create duplicated columns for the DataTable, and the whole solution should be it that you should create a DataTable schema first, and then use a foreach to loop and assign values to the DataTable:

    result = new DataTable();

    result.Columns.Add("ID", typeof(Int32));
    result.Columns.Add("Color", typeof(Int32));
    result.Columns.Add("Size",typeof(Int32));

    foreach (var itm in query.ToList())
                    {
                        var sizeTotal = itm.Data.Sum(c => c.qty);
                        foreach (var itm2 in itm.Data)
                        {
                            result.Rows.Add(itm2.Id,itm.Color,sizeTotal);       
                        }
                    }


     

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 13, 2011 9:24 PM