Reputation: 634
I have a linq statement from a dataset I am retrieving. The problem is there is one field that can be string or numeric TYPE depending on what table I pull the information from. (Both tables have the same field names). Here is the linq:
List<clsTableData> allFieldsList = (from g in ds.Tables["Default"].AsEnumerable()
select new clsTableData
{
tableName = g.Field<string>("tablename"),
custAccount = int.TryParse(g.Field<string>("accountNum"), out result) ?
Convert.ToInt32(g.Field<System.Int64>("accountNum")) :
12345
}
).ToList();
Now if the field type is string, it works. If it is numeric, it gives me an error of "Unable to cast object of type System.Int64 to type System.String". However, the value is already being placed in an int (custAccount):
public class clsTableData
{
public string tableName { get; set; }
public int custAccount { get; set; }
}
It seems there is a problem in the int.TryParse. (I am not bound to using int.TryParse. I actually think the correct solution is to find out if the field type is integer instead of checking the field value) Any help would be appreciated.
Answer
Thanks to MethodMan it has been resolved:
List<clsTableData> allFieldsList = (from g in ds.Tables["Default"].AsEnumerable()
select new clsTableData
{
tableName = g.Field<string>("tablename"),
custAccount = g["accountNum"].GetType() == typeof(System.Int64) ?
Convert.ToInt32(g.Field<System.Int64>("accountNum")) :
12345
}
).ToList();
Upvotes: 2
Views: 2382
Reputation: 634
Thanks to MethodMan! Here is the answer:
List<clsTableData> allFieldsList = (from g in ds.Tables["Default"].AsEnumerable()
select new clsTableData
{
tableName = g.Field<string>("tablename"),
custAccount = g["accountNum"].GetType() == typeof(System.Int64) ?
Convert.ToInt32(g.Field<System.Int64>("accountNum")) :
12345
}
).ToList();
Upvotes: 1
Reputation: 152604
You can check the the field type directly rather then by inferring it:
select new clsTableData
{
tableName = g.Field<string>("tablename"),
custAccount = dtRow.Table.Columns["accountNum"].DataType == typeof(System.Int64) ?
Convert.ToInt32(g.Field<System.Int64>("accountNum")) :
12345
}
Upvotes: 0
Reputation: 1535
You could call ToString()
on it so that you are always converting from a string object.
List<clsTableData> allFieldsList = (from g in ds.Tables["Default"].AsEnumerable()
select new clsTableData
{
tableName = g.Field<string>("tablename"),
custAccount = int.TryParse((g.Field<string>("accountNum")).ToString(), out result) ?
Convert.ToInt32(g.Field<System.Int64>("accountNum")) :
12345
}
).ToList();
Upvotes: 0