views:

91

answers:

1

I'm trying to do the following:

from c in db.GetAllContactsQuery()
select new
{
   ID= c.ID,
   LastName = c.LastName,
   FirstName = c.FirstName,
   Email = c.Email,
   City =c.City+" "+c.State
}

The issue i'm running into is that if c.City or c.State are null, the City property returns null. How can I put a function right beside that City= declaration?

I'd really like to know if its possible to do something like this (this does not work):

from c in db.GetAllContactsQuery()
select new
{
   ID= c.ID,
   LastName = c.LastName,
   FirstName = c.FirstName,
   Email = c.Email,
   City ={ c=>
         //completely sweet function in here
         if(String.IsNullOrEmpty(c.City))
                return "booyah";
   }
}
+4  A: 

Use a null coalescing operator? If the value on the left of ?? is null, it is substituted for the value on the right.

from c in db.GetAllContactsQuery()
select new
{
   ID= c.ID,
   LastName = c.LastName,
   FirstName = c.FirstName,
   Email = c.Email,
   City =(c.City??"")+" "+(c.State??"")
}

In answer to your comment, you need to use AsEnumerable so you can use full CLR goodness:

db.GetAllContactsQuery()
    .AsEnumerable()
    .Select(c=>new
        {
           ID= c.ID,
           LastName = c.LastName,
           FirstName = c.FirstName,
           Email = c.Email,
           City =MyClrMethod(c.City,c.State)
        })

If db.GetAllContactsQuery() returns many additional fields, select the ones of interest before the AsEnumerable clause to narrow bandwidth requirements.

spender
I believe you are right, but is there any way to open up a function here, in case i want to do some more logic? Such as special formatting based upon the country they live in
Micah
Is this Linq to Objects or Linq2SomethingElse?
spender
Its being run off of LinqToSql
Micah
Why is that AsEnumberable required?
Micah
Linq to Sql only supports a limited number of methods. AsEnumerable effectively turns your Linq2Sql into Linq2Objects which allows access to the full CLR.
spender
http://stackoverflow.com/questions/2512639/switching-from-linqtoxyz-to-linqtoobjects
spender
Ahhh. Thank you for throwing that link in there I had no idea about the underpinnings of AsEnumerable. Thanks again!
Micah