首页 > 编程语言 >C# 将JArray转换为datatable

C# 将JArray转换为datatable

时间:2022-10-20 17:00:04浏览次数:44  
标签:Count C# JArray dataArr DataTable datatable

        /// <summary>
        /// 将JArray转换为datatable
        /// </summary>
        /// <param name="dataArr"></param>
        /// <returns></returns>
        private DataTable JArrayToDatable(JArray dataArr)
        {
            if (dataArr == null || dataArr.Count <= 0) return null;

            DataTable result = new DataTable();
            var colnames = ((JObject)dataArr.First).Properties();
            List<string> columnNames = new List<string>();

            if (colnames == null || colnames.Count() <= 0) return null;

            foreach (var item in colnames)
            {
                if (!columnNames.Contains(item.Name))
                {
                    columnNames.Add(item.Name);
                }
                result.Columns.Add(item.Name, typeof(string));
            }
            foreach (JObject data in dataArr)
            {
                JObject jo = JObject.Parse(data.ToString());
                DataRow row = result.NewRow();
                foreach (var columnName in columnNames)
                {
                    if (jo.Property(columnName) == null)
                    {
                        data.Add(columnName, "");
                        row[columnName] = data[columnName].ToString();
                    }
                    else
                    {
                        row[columnName] = data[columnName].ToString();
                    }
                }
                result.Rows.Add(row);
            }
            return result;
        }

DataTable data = JArrayToDatable(JArray.FromObject(model.Items));

标签:Count,C#,JArray,dataArr,DataTable,datatable
From: https://www.cnblogs.com/duhaoran/p/16810463.html

相关文章