2012-05-15 44 views
5

我不得不选择从我的DataTable中使用LINQ 特定列我使用这个代码如何在LINQ中选择特定列?

ds.Table[0].AsEnumerable().Where<DataRow>(r=>r.Field<int>("productID")==23).CopyToDataTable(); 

但它给我的所有列,我只需要产品名称,描述,价格

我如何写这个查询?

回答

4

要扩大@lazyberezovsky一点,你可以使用匿名类型的投影得到你想要的所有字段:

ds.Table[0].AsEnumerable() 
    .Where<DataRow>(r => r.Field<int>("productID") == 23) 
    .Select(r => new { ProductName = r.Field<string>("productName"), 
         Description = r.Field<string>("description"), 
         Price = r.Field<decimal>("price") }); 

我不知道是什么名字,然后键入您的产品名称,描述,和价格领域,所以你将不得不取代这些。

+0

谢谢它的作品。你问我的问题,你的答案是我的问题的答案。我已经知道如何显示一个字段,但不知道如何显示3 – user1390378

6

使用选择方法:

ds.Table[0].AsEnumerable() 
      .Where<DataRow>(r=>r.Field<int>("productID")==23) 
      .Select(r => r.Field<int>("productID")); 

UPDATE:如果您需要选择多列,可以返回匿名类型:

var query = from row in dt.ds.Table[0].AsEnumerable() 
      where row.Field<int>("productID")==23 
      select new { 
          ProductID = x.Field<string>("productID"), 
          Foo = x.Field<string>("foo") 
         }; 

如果您需要将数据复制到新表,你会面临问题(CopyToDataTable需要收集DataRow对象)。请参阅How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow来解决此问题。

+0

通过这个,我可以选择只有一列,但我必须选择3 – user1390378