您的位置:首页 > 编程学习 > ASP.NET > 正文

Linq操作Datable

更多 时间:2017-8-28 类别:编程学习 浏览量:694

Linq操作Datable

Linq操作Datable

一、Datable简单查询

  •  
  •  
  • C# 代码   复制
  • 
    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);
    }
    
    		
  •  

    二、Datable代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")
        });
    
    		
  •  

    三、DataTable数据排序

     

  • 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 ds.Tables["Product"].AsEnumerable()
               orderby p.Field<int>("SortOrder"), p.Field<string>("ProductName") descending
               select p;
    
    				
  •  

    四、多个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")
                };
    
    		
  •  

    五、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"));
        }
    }
    
    		
  •  

    标签:Linq Datable