prodInfosDT是一个datatable
var prods1 = from dataRow in prodInfosDT.AsEnumerable()
select new { ProductId = dataRow.Field<string>("product_id"), ProductName = dataRow.Field<int>("product_name") };
var pids1 = prods1.Select(c => c.ProductId); //这里会报错 说decimal不能转化为string var prods2 = from dataRow in prodInfosDT.AsEnumerable()
select new { ProductId = dataRow["product_id"].TryString(), ProductName = dataRow["product_name"].TryString() };
var pids2 = prods2.Select(c => c.ProductId); //这里就不会报错两种写法不应该有什么区别的啊 为什么会这样?反正就是 dataRow.Field<string>("product_id")这种写法query出来的数据列表不能进行select 操作 哪位大大能解释下?
var prods1 = from dataRow in prodInfosDT.AsEnumerable()
select new { ProductId = dataRow.Field<string>("product_id"), ProductName = dataRow.Field<int>("product_name") };
var pids1 = prods1.Select(c => c.ProductId); //这里会报错 说decimal不能转化为string var prods2 = from dataRow in prodInfosDT.AsEnumerable()
select new { ProductId = dataRow["product_id"].TryString(), ProductName = dataRow["product_name"].TryString() };
var pids2 = prods2.Select(c => c.ProductId); //这里就不会报错两种写法不应该有什么区别的啊 为什么会这样?反正就是 dataRow.Field<string>("product_id")这种写法query出来的数据列表不能进行select 操作 哪位大大能解释下?
如果转换不了,就是空字符而<string>("product_id")不是这样的
pids1[0]
Cannot apply indexing with [] to an expression of type 'System.Data.EnumerableRowCollection<string>'看吧 问题好像是在dataRow.Field<T>(string str) 本身
如果是int的话,好像应该是dataRow.Field<int>("product_id")参考
http://blog.sina.com.cn/s/blog_489e41680100fmpk.html
另外,如果
var prods1 = from dataRow in prodInfosDT.AsEnumerable()
select new { ProductId = dataRow.Field<string>("product_id"), ProductName = dataRow.Field<int>("product_name") };
不报错在后面添加
foreach(var each in prods1)
{
Console.WriteLine(each.ProductId);
Console.WriteLine(each.ProductId.GetType());
}看看是什么类型的。
数据库的表CREATE TABLE [dbo].[Test](
[id] [int] IDENTITY(1,1) NOT NULL,
[BoolField] [bit] NOT NULL
) ON [PRIMARY]
代码var query = from dataRow in entlib4DataSet.Tables[0].AsEnumerable()
select new {DataId = dataRow.Field<int>("id"), ValueType = dataRow.Field<bool>("BoolField")};var pids1 = query.Select(c => c.DataId);int sum = 0;
foreach (var each in pids1)
{
sum += each;
}
Field 方法不执行类型转换。如果要求类型转换,则应首先使用 Field 方法来获取列值。然后,应将列值转换为其他类型
顶啊
问题就出在
楼主认为Field方法本身含有类型转换的功能了
其实Field<T>只是说明某字段是T这种类型而已,
并不表示它具有能将其他类型转换成T类型的能力
var query =
from product in products.AsEnumerable()
where !product.IsNull("Color") &&
(string)product["Color"] == "Red"
select new
{
Name = product["Name"],
ProductNumber = product["ProductNumber"],
};