• linq 查询结果转换成DataTable 方法


    转换方法代码:

    代码
     private DataTable ConvertToTable(IQueryable query)
            {
                DataTable dtList 
    = new DataTable();
                
    bool isAdd = false;
                PropertyInfo[] objProterties 
    = null;
                
    foreach (var item in query)
                {
                    
    if (!isAdd)
                    {
                        objProterties 
    = item.GetType().GetProperties();
                        
    foreach (var itemProterty in objProterties)
                        {
                            Type type 
    = null;
                            
    if (itemProterty.PropertyType != typeof(string&& itemProterty.PropertyType != typeof(int&& itemProterty.PropertyType != typeof(DateTime))
                            {
                                type 
    = typeof(string);
                            }
                            
    else
                            {
                                type 
    = itemProterty.PropertyType;
                            }
                            dtList.Columns.Add(itemProterty.Name, type);
                        }
                        isAdd 
    = true;
                    }
                    var row 
    = dtList.NewRow();
                    
    foreach (var pi in objProterties)
                    {
                        row[pi.Name] 
    = pi.GetValue(item, null);
                    }
                    dtList.Rows.Add(row);
                }

                
    return dtList;
            }


    调用方法:

    //linq查询语句
    var queryData =
                                from dv 
    in emcsDataContext.DailyVals
                                join vrb 
    in emcsDataContext.Variables on dv.VariableID equals vrb.VariableID
                                
    where dv.VariableID == variableId && dv.CollectTime >= selectDate && dv.CollectTime < selectDate.AddDays(1)
                                orderby dv.CollectTime
                                select 
    new
                                {
                                    dv.ID,
                                    dv.VariableID,
                                    dv.CollectTime,
                                    dv.VariableValue,
                                    vrb.UpLimite,
                                    vrb.LowLimite,
                                    statDate 
    = dv.CollectTime.ToShortTimeString()
                                };
    //转换
    ConvertToTable(queryData)


  • 相关阅读:
    钉钉outgoing机器人小项目开发
    js根据cookie判断,一天之内只弹出一次弹窗
    js倒计时功能
    jquery的$().each,$.each的区别
    VS代码提示自动高亮
    winform当前屏幕大小
    动态增删改控件
    datagridveiw样式
    sql 语句 提取中文的首字母
    按键监听及重写
  • 原文地址:https://www.cnblogs.com/scottckt/p/1786007.html
Copyright © 2020-2023  润新知