0

I am trying get the max value of a ushort type column from a DataTable.

It throws up "Specified Cast is Not Valid"

Here is the query

var c = DSFinyr.Tables[0].AsEnumerable().Max(p => p.Field<ushort>("finid"));

tried with int also. same error.

How do i cast this ?

thanks

Deb
  • 981
  • 13
  • 39

1 Answers1

2

The equivalent to SQL Server smallint in c# is short, not ushort. And if the field is nullable, then you need to use short? like this:

var c = DSFinyr.Tables[0].AsEnumerable().Max(p => p.Field<short?>("finid"));
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
  • The equivalent to SMALLINT is Int16, not int or short. Not that it matters that much, you can cast an Int16 to an int or short. – Jim Nov 23 '15 at 20:03
  • See this for SQL Server to .NET equavalents... http://stackoverflow.com/a/968734/1246574 – Jim Nov 23 '15 at 20:04
  • as i have said the value in the field is numeric 1. It is a not null. – Deb Nov 23 '15 at 20:05
  • 1
    @jim, but `short` is `int16`. See [MSDN](https://msdn.microsoft.com/en-us/library/ybs77ex4.aspx). – Racil Hilan Nov 23 '15 at 20:06
  • @Deb, You did not say it is Numeric, you said SMALLINT. You said it right in the comments on your OP. – Jim Nov 23 '15 at 20:06
  • @Deb It doesn't matter what the value is. If today's value is not null, you may have a null in the future. The important thing is the type of the field. If it is nullable, then you need to use the nullable type in C#. – Racil Hilan Nov 23 '15 at 20:09
  • By Numeric i mean number (Not Character) . Sorry for the misunderstanding. – Deb Nov 23 '15 at 20:10
  • @RacilHilan The Column Type shows Int16, But when you check Row data members it is ushort. Thanks anyway. Upvoted. – Deb Nov 23 '15 at 20:17
  • @Deb Yes, the Column Type is what matters, not the raw data. So you can use `Int16` or `short`. Both are equivalent in C#. – Racil Hilan Nov 23 '15 at 20:20