当前位置:   article > 正文

datatable linq 查询排序用法总结_c# datatable linq 查询

c# datatable linq 查询

DataTable通过调用AsEnumerable()方法,从而运用Linq查询。其中AsEnumerable方法在System.Data.DataSetExtensions.dll中定义,一般VS会自动引用这个dll。

一、datatable linq查询实例

1. DataTable读取列表

DataSet ds = new DataSet();
// 省略ds的Fill代码
DataTable products = ds.Tables["Product"];
var rows = products.AsEnumerable()
    .Select(p => new
    {
        ProductID = p.Field<int>("ProductID"),
        ProductName = p.Field<string>("ProductName"),
        UnitPrice = p.Field<decimal>("UnitPrice")
    });
foreach (var row in rows)
{
    Console.WriteLine(row.ProductName);
}

2. DataTable linq where 查询

C# 代码    复制

var rows = products.AsEnumerable()
    .Where(p => p.Field<decimal>("UnitPrice") > 10m)
    .Select(p => new
    {
        ProductID = p.Field<int>("ProductID"),
        ProductName = p.Field<string>("ProductName"),
        UnitPrice = p.Field<decimal>("UnitPrice")
    });

3、DataTable linq 数据排序

C# 代码    复制

var rows = products.AsEnumerable()
    .Where(p => p.Field<decimal>("UnitPrice") > 10m)
    .OrderBy(p => p.Field<int>("SortOrder"))
    .Select(p => new
    {
        ProductID = p.Field<int>("ProductID"),
        ProductName = p.Field<string>("ProductName"),
        UnitPrice = p.Field<decimal>("UnitPrice")
    });

C# 代码    复制

var expr = from p in products.AsEnumerable()
            orderby p.Field<int>("SortOrder")
            select p;
IEnumerable<DataRow> rows = expr.ToArray();
foreach (var row in rows)
{
    Console.WriteLine(row.Field<string>("ProductName"));
}

C# 代码    复制

var expr = from p in ds.Tables["Product"].AsEnumerable()
           orderby p.Field<int>("SortOrder"), p.Field<string>("ProductName") descending
           select p;

4、DataTable分组 

C# 代码    复制

var query = from p in ds.Tables["Product"].AsEnumerable()
            group p by p.Field<int>("CategoryID") into g
            select new
            {
                CategoryID = g.Key,
                Products = g
            };

foreach (var item in query)
{
    Console.WriteLine(item.CategoryID);
    foreach (var p in item.Products)
    {
        Console.WriteLine(p.Field<string>("ProductName"));
    }
}

查询Product中每个CategoryID的数目

C# 代码    复制

var expr = from p in ds.Tables["Product"].AsEnumerable()
           group p by p.Field<int>("CategoryID") into g
           select new
           {
               CategoryID = g.Key,
               ProductsCount = g.Count()
           };

5、多个DataTable查询

C# 代码    复制

var query = from p in ds.Tables["Product"].AsEnumerable()
            from c in ds.Tables["Category"].AsEnumerable()
            where p.Field<int>("CategoryID") == c.Field<int>("CategoryID")
                && p.Field<decimal>("UnitPrice") > 10m
            select new
            {
                ProductID = p.Field<int>("ProductID"),
                ProductName = p.Field<string>("ProductName"),
                CategoryName = c.Field<string>("CategoryName")
            };

二、linq 对象转换为DataTable

通过CopyToDataTable()方法

C# 代码    复制

DataTable newD1t = query1.CopyToDataTable<DataRow>();
            foreach (DataRow item in newD1t.Rows)
            {
                System.Console.WriteLine(item["Name"]);
            }

需求:从DataTable中直接生成指定类的对象或对象列表

使用:datatable.ToListModel<T>();

代码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Web;
  6. /// <summary>
  7. /// DataTableToModel 的摘要说明
  8. /// </summary>
  9. public static class DataTableToModel
  10. {
  11. /// <summary>
  12. /// DataTable通过反射获取单个像
  13. /// </summary>
  14. public static T ToSingleModel<T>(this DataTable data) where T : new()
  15. {
  16. T t = data.GetList<T>(null, true).Single();
  17. return t;
  18. }
  19. /// <summary>
  20. /// DataTable通过反射获取单个像
  21. /// <param name="prefix">前缀</param>
  22. /// <param name="ignoreCase">是否忽略大小写,默认不区分</param>
  23. /// </summary>
  24. public static T ToSingleModel<T>(this DataTable data, string prefix, bool ignoreCase = true) where T : new()
  25. {
  26. T t = data.GetList<T>(prefix, ignoreCase).Single();
  27. return t;
  28. }
  29. /// <summary>
  30. /// DataTable通过反射获取多个对像
  31. /// </summary>
  32. /// <typeparam name="type"></typeparam>
  33. /// <param name="type"></param>
  34. /// <returns></returns>
  35. public static List<T> ToListModel<T>(this DataTable data) where T : new()
  36. {
  37. List<T> t = data.GetList<T>(null, true);
  38. return t;
  39. }
  40. /// <summary>
  41. /// DataTable通过反射获取多个对像
  42. /// </summary>
  43. /// <param name="prefix">前缀</param>
  44. /// <param name="ignoreCase">是否忽略大小写,默认不区分</param>
  45. /// <returns></returns>
  46. private static List<T> ToListModel<T>(this DataTable data, string prefix, bool ignoreCase = true) where T : new()
  47. {
  48. List<T> t = data.GetList<T>(prefix, ignoreCase);
  49. return t;
  50. }
  51. private static List<T> GetList<T>(this DataTable data, string prefix, bool ignoreCase = true) where T : new()
  52. {
  53. List<T> t = new List<T>();
  54. int columnscount = data.Columns.Count;
  55. if (ignoreCase)
  56. {
  57. for (int i = 0; i < columnscount; i++)
  58. data.Columns[i].ColumnName = data.Columns[i].ColumnName.ToUpper();
  59. }
  60. try
  61. {
  62. var properties = new T().GetType().GetProperties();
  63. var rowscount = data.Rows.Count;
  64. for (int i = 0; i < rowscount; i++)
  65. {
  66. var model = new T();
  67. foreach (var p in properties)
  68. {
  69. var keyName = prefix + p.Name + "";
  70. if (ignoreCase)
  71. keyName = keyName.ToUpper();
  72. for (int j = 0; j < columnscount; j++)
  73. {
  74. if (data.Columns[j].ColumnName == keyName && data.Rows[i][j] != null)
  75. {
  76. string pval = data.Rows[i][j].ToString();
  77. if (!string.IsNullOrEmpty(pval))
  78. {
  79. try
  80. {
  81. // We need to check whether the property is NULLABLE
  82. if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
  83. {
  84. p.SetValue(model, Convert.ChangeType(data.Rows[i][j], p.PropertyType.GetGenericArguments()[0]), null);
  85. }
  86. else
  87. {
  88. p.SetValue(model, Convert.ChangeType(data.Rows[i][j], p.PropertyType), null);
  89. }
  90. }
  91. catch(Exception x) {
  92. throw x;
  93. }
  94. }
  95. break;
  96. }
  97. }
  98. }
  99. t.Add(model);
  100. }
  101. }
  102. catch (Exception ex)
  103. {
  104. throw ex;
  105. }
  106. return t;
  107. }
  108. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/418932
推荐阅读
相关标签
  

闽ICP备14008679号