none
I have a data table with 4 coloums where I want distinct of 1 and last column and sum of remaining to columns using linq or Select statement please help me to achieve this RRS feed

  • Question

  • I have a data table with 4 colunms where I want distinct of 1 and last column and sum of remaining to columns using linq or Select statement please help me to achieve this
    Tuesday, May 8, 2018 4:33 AM

All replies

  • Hi Tasnim Iram,

    Here is simple sample, which use LINQ and datatable for your reference.

    class Program
        {
            static void Main(string[] args)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("Name", Type.GetType("System.String"));
                dt.Columns.Add("Price", Type.GetType("System.Double"));
                dt.Columns.Add("New", Type.GetType("System.Double"));
                dt.Columns.Add("Location", Type.GetType("System.String"));
    
                DataRow dr = dt.NewRow();
                dr["Name"] = "item1";
                dr["Price"] = 6;
                dr["New"] = 15;
                dr["Location"] = "AB";
    
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["Name"] = "item2";
                dr["Price"] = 5;
                dr["New"] = 11;
                dr["Location"] = "AB";
                dt.Rows.Add(dr);
    
                dr = dt.NewRow();
                dr["Name"] = "item1";
                dr["Price"] = 7;
                dr["New"] = 13;
                dr["Location"] = "AB";
                dt.Rows.Add(dr);
    
                dr = dt.NewRow();
                dr["Name"] = "item1";
                dr["Price"] = 10;
                dr["New"] = 15;
                dr["Location"] = "AB";
                dt.Rows.Add(dr);
    
                var group = dt.AsEnumerable().GroupBy(row => new
                {
                    Name = row.Field<string>("Name"),
                    Location = row.Field<string>("Location")
                })
                .Select(t => new
                {
                    Name =  t.Key.Name,
                    Location = t.Key.Location,
                    SumPrice = t.Sum(z => z.Field<Double>("Price")),
                    SumNew = t.Sum(z => z.Field<Double>("New"))
                }
                ).ToList();
    
                Console.ReadKey();    
                    
           }
    }

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, May 8, 2018 8:05 AM
    Moderator