0

Hi i have a Linq to Entity Statement that returns a Zipcode.
and I store this return Zip code in my strongly typed Lists
In my List Zipcode Data type is int
when my Liq statement returns Zipcode there are some NULL and Empty values
and I am not able to convert these NULL and Empty values to int
how can i handle this situation.
I tried something like this

ZipCode= Convert.ToInt32(p.ZipCode ?? "0")

any help is greatly appreciated.

thanks

Aducci
  • 26,101
  • 8
  • 63
  • 67
HaBo
  • 13,999
  • 36
  • 114
  • 206

3 Answers3

1

If you are doing this in memory (after results have already been pulled from the database), and to do that in one line, you would write something like

int zip = Convert.ToInt32(!string.IsNullOrEmpty(p.ZipCode) ? p.ZipCode : "0");

If you are trying to convert the string to an integer inside query at the database, you might have to define a custom defined function that will translate a conversion to the proper cast at the database. See this related question for a possible implementation.

However, I would encourage you not to convert a zip code to an integer. A zip is not a numeric value, despite being composed of numbers (in parts of the world). Treat it as a proper string, which it looks like you are already doing inside p (and presumably the database). The same premise applies to phone numbers, SSNs, account numbers, etc.

Community
  • 1
  • 1
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
0

Without seeing your actual query and assuming p.ZipCode is a string, you can do something like this in order to convert to int

var query = from p in context.Entity
            let ZipCode = context.Entity.Take(1).Select(x => (p.ZipCode == null || p.ZipCode == "") ? "0" : p.ZipCode).Cast<int>().FirstOrDefault()
            select ZipCode;
Aducci
  • 26,101
  • 8
  • 63
  • 67
0

I would start out by defining a lambda function that will parse your integer, like so:

Func<string, int> parse = t =>
{
    int v;
    if (!int.TryParse(t, out v))
    {
        v = 0;
    }
    return v;
};

Then you just need to do this:

var zipCodes =
    from e in db.Entity
    select parse(e.ZipCode);

Nice and simple!

Enigmativity
  • 113,464
  • 11
  • 89
  • 172