[ACCEPTED]-How to know if a field is numeric in Linq To SQL-linq-to-sql

Accepted answer
Score: 15

Open up your DBML (LINQ-to-SQL) file in 5 an XML editor, go down to the end of the 4 file and paste this just before the '</Database>' node:

<Function Name="ISNUMERIC" IsComposable="true">
    <Parameter Name="Expression" Parameter="Expression" Type="System.String" DbType="NVarChar(4000)" />
    <Return Type="System.Boolean" DbType="BIT NOT NULL"/>

Now, you 3 can use the already-in-SQL function called "ISNUMERIC". Here's 2 how:

var blah = myDataContext.Accounts.Where(account=>
    myDataContext.ISNUMERIC(account.ID) == true);

There you go :)

You may also find these 1 functions useful to copy:

<Function Name="RAND" IsComposable="true">
  <Return Type="System.Double" DbType="Float NOT NULL" />
<Function Name="NEWID" IsComposable="true">
  <Return Type="System.Guid" DbType="UniqueIdentifier NOT NULL" />
Score: 7

I don't know if there is a mapping for int.TryParse() in 8 LinqToSQL, but you could probably do it 7 in two steps by performing the query, casting 6 to a List, then selecting out of the list 5 with LinqToObjects.

int i;
var query = context.Table.ToList();
var intQuery = query.Where( t => int.TryParse( t.Column, out i ) );

You might want to look 4 at Dynamic LINQ, too. That would allow you to do something 3 like:

var query = context.Table.Where( "IsNumeric(Column)" );

EDIT Dynamic LINQ is available in the VS2008 2 Code Samples, linked to from Scott Guthrie's 1 blog, which I've linked above.

Score: 5



For example:

    private int GetLastGoodNumber(string PartNum)
        return (from row in Db.SerialNo
                   row.PartNum == PartNum
                let nullable = System.Data.Objects.SqlClient.SqlFunctions.IsNumeric(row.SerialNumber)
                where nullable != null
                select nullable.Value).Max();


Score: 1


Score: 0

Look into Int32.TryParse ... That may work 1 for you.


More Related questions