I am using linq to cast data row to MapValueFields class, but row values are strings, so it trigger casting error, any help is appreciated.
Inside class
public partial class MapValueFields
{
public GrandTotal Amount { get; set; }
...
}
public partial class GrandTotal
{
public string DoubleValue { get; set; }
}
I tried this
List<MapValueFields> items = viewLaundry.ToTable().Rows.Cast<DataRow>().Select(t => new MapValueFields()
{
Amount = t.Field<GrandTotal>("Total Amount"), // here is the problem
...
}).ToList();
casting error say string not cast to the GrandTotal
CodePudding user response:
I think the value in the column is a string. Just because a GrandTotal has a string does not mean it is a string. Cast can only perform is-a conversions. You'll have to make a new object and assign the string to the relevant property
List<MapValueFields> items = viewLaundry.ToTable().Rows.Cast<DataRow>().Select(t => new MapValueFields()
{
Amount = new GrandTotal { DoubleValue = t.Field<string>("Total Amount")
...
}).ToList();
You could also use (string)t["Total Amount"]
for a more compact syntax
CodePudding user response:
In case for other users
Amount = new GrandTotal() { DoubleValue = t.Field<string>("Total Amount") },