如何在 linq 中将数据转换为嵌套的 class
How to cast data to nested class in linq
我正在使用 linq 将数据行转换为 MapValueFields class,但是行值是字符串,因此它会触发转换错误,我们将不胜感激。
里面class
public partial class MapValueFields
{
public GrandTotal Amount { get; set; }
...
}
public partial class GrandTotal
{
public string DoubleValue { get; set; }
}
我试过了
List<MapValueFields> items = viewLaundry.ToTable().Rows.Cast<DataRow>().Select(t => new MapValueFields()
{
Amount = t.Field<GrandTotal>("Total Amount"), // here is the problem
...
}).ToList();
转换错误说字符串未转换为 GrandTotal
以防其他用户
Amount = new GrandTotal() { DoubleValue = t.Field<string>("Total Amount") },
我认为列中的值是一个字符串。仅仅因为 GrandTotal 有一个 字符串并不意味着它 是一个 字符串。 Cast 只能执行 is-a 次转换。您必须创建一个新对象并将字符串分配给相关的 属性
List<MapValueFields> items = viewLaundry.ToTable().Rows.Cast<DataRow>().Select(t => new MapValueFields()
{
Amount = new GrandTotal { DoubleValue = t.Field<string>("Total Amount")
...
}).ToList();
您还可以使用 (string)t["Total Amount"]
以获得更紧凑的语法
我正在使用 linq 将数据行转换为 MapValueFields class,但是行值是字符串,因此它会触发转换错误,我们将不胜感激。
里面class
public partial class MapValueFields
{
public GrandTotal Amount { get; set; }
...
}
public partial class GrandTotal
{
public string DoubleValue { get; set; }
}
我试过了
List<MapValueFields> items = viewLaundry.ToTable().Rows.Cast<DataRow>().Select(t => new MapValueFields()
{
Amount = t.Field<GrandTotal>("Total Amount"), // here is the problem
...
}).ToList();
转换错误说字符串未转换为 GrandTotal
以防其他用户
Amount = new GrandTotal() { DoubleValue = t.Field<string>("Total Amount") },
我认为列中的值是一个字符串。仅仅因为 GrandTotal 有一个 字符串并不意味着它 是一个 字符串。 Cast 只能执行 is-a 次转换。您必须创建一个新对象并将字符串分配给相关的 属性
List<MapValueFields> items = viewLaundry.ToTable().Rows.Cast<DataRow>().Select(t => new MapValueFields()
{
Amount = new GrandTotal { DoubleValue = t.Field<string>("Total Amount")
...
}).ToList();
您还可以使用 (string)t["Total Amount"]
以获得更紧凑的语法