开发者

Copying Result of Linq into DataTable

What changes do i need to make so as to reduce of doing this task with fewer lines and better approach.

   DataTable dtStatusMsgs;
    var statusList = (
                    from items in dtInputTable.AsEnumerable()
                    where items.Field<int>("DepartmentId") == deptId
                    select new
                    {
                        statusId = items.Field<int>("StatusId"),
                        status = items.Field<string>("Status"),
                        statusOrder = items.Field<int>("StatusSortOrder"),
                        rowId = items.Field<int>("RowId")

            开发者_高级运维        }).Distinct();

    dtStatusMsgs = new DataTable();
    dtStatusMsgs.Columns.Add("StatusId", typeof(int));
    dtStatusMsgs.Columns.Add("Status", typeof(string));
    dtStatusMsgs.Columns.Add("StatusSortOrder", typeof(int));
    dtStatusMsgs.Columns.Add("RowId", typeof(int));

    foreach (var item in statusList)
        dtStatusMsgs.Rows.Add(item.statusId, item.status,item.statusOrder
                              , item.rowId);

I want it to be done something like this.

   DataTable dtStatusMsgs;
    var statusList = (
                    from items in dtInputTable.AsEnumerable()
                    where items.Field<int>("DepartmentId") == deptId
                    select new
                    {
                        statusId = items.Field<int>("StatusId"),
                        status = items.Field<string>("Status"),
                        statusOrder = items.Field<int>("StatusSortOrder"),
                        rowId = items.Field<int>("RowId")

                    }).Distinct();



dtStatusMsgs= statusList.CopyToDataTable<DataRow>();

And how to use Sum function on any of the column in this code. I want to see a sample code on this for applying any aggregate function


dtStatusMsgs = new DataTable();     
dtStatusMsgs.Columns.Add("StatusId", typeof(int));     
dtStatusMsgs.Columns.Add("Status", typeof(string));     
dtStatusMsgs.Columns.Add("StatusSortOrder", typeof(int));     
dtStatusMsgs.Columns.Add("RowId", typeof(int));

statusList.ForEach(p => dtStatusMsgs.Rows.Add(p.StatusId, p.Status, p.StatusSortOrder,p.RowId)); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜