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 操作   哪位大大能解释下?

解决方案 »

  1.   

    TryString()这个会做主动转换
    如果转换不了,就是空字符而<string>("product_id")不是这样的
      

  2.   

    把 dataRow.Field<string>("product_id") 改为 dataRow["product_id"] as string
      

  3.   

    以上3楼全部没有理解我的意思  dataRow.Field<string>("product_id")这个返回本身就是一个string  而且我的datatable没有空值  暂时不用考虑空值问题  
      

  4.   

    dataRow.Field<string>("product_id")感觉应该是product_id是整形,没办法转换为字符串dataRow.Field<int>("product_id").ToString()这样可以吗?
      

  5.   


    pids1[0]
    Cannot apply indexing with [] to an expression of type 'System.Data.EnumerableRowCollection<string>'看吧  问题好像是在dataRow.Field<T>(string str)  本身
      

  6.   

    设个断点, 看看dataRow["product_id"] 是什么类型的?
    如果是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());
    }看看是什么类型的。
      

  7.   

    写了测试工程,我这里没有问题
    数据库的表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;
    }
      

  8.   

    MSDN中写的:
    Field 方法不执行类型转换。如果要求类型转换,则应首先使用 Field 方法来获取列值。然后,应将列值转换为其他类型
      

  9.   


    顶啊
    问题就出在
    楼主认为Field方法本身含有类型转换的功能了
    其实Field<T>只是说明某字段是T这种类型而已,
    并不表示它具有能将其他类型转换成T类型的能力
      

  10.   

    Field 方法不执行类型转换
    var query =
        from product in products.AsEnumerable()
        where !product.IsNull("Color") &&
            (string)product["Color"] == "Red"
        select new
        {
            Name = product["Name"],
            ProductNumber = product["ProductNumber"],
        };