tsilb
tsilb

Reputation: 8037

?: Operator in LINQ Query

Upvotes: 10

Views: 14545

Answers (5)

LeppyR64
LeppyR64

Reputation: 5349

I'm fairly new to Linq to SQL but I'm pretty sure it would go like this:

var query =
    from a in db.tblActivities
    from i in a.tblIPs
    from u in i.tblUsers 
    select new
    {
        userName = (u.UserName == null)
            ? i.Address
            : u.UserName,
        a.Request,
        a.DateTime
    };

The if statement needs to be in parentheses and the results outside of them. As for the joins, you follow the chain down from one->many.

Upvotes: 0

user36784
user36784

Reputation: 23

Really. this question depends on the particular implementation of IQueryable that your linq expression will return. I see that you have db.XXX so are you using linq to sql or some linq to data store? If so, the specific implementation of IQueryable will need to have a way to translate your expression into a store expression. Other than the above comments, some of the other comments are correct that in an anonymous type you must specify a name for each member. This is really your error.

Upvotes: 0

GalacticCowboy
GalacticCowboy

Reputation: 11759

When creating an anonymous type (what you're doing with the "new" without specifying a type) you have to specify the member name for each property. From your example, it would look something like this: (also fixed your joins)

var query = from a in db.tblActivities
            join i in db.tblIPs on a.ipid equals i.id
            join u in db.tblUsers on i.uid equals u.id
            select new {
               UserName = (u.UserName ?? i.Address),
               Request = a.Request,
               Date = a.DateTime
            };

You could probably do the UserName your way, too:

UserName = (u.UserName == null) ? i.Address : u.UserName,

but the ?? operator is more concise. It's similar to "isnull" in SQL.

Upvotes: 19

hugoware
hugoware

Reputation: 36397

if you're checking just for null, you can also use ??

string something = null;
string somethingElse = something ?? "default value";

As for the examples above, it is correct to do the ones that go...

string something = (somethingElse == null ? "If it is true" : "if it is false");

The parens aren't required, but they do aid in reading.

Upvotes: 0

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827546

You have to use the join keyword, and define the relationship between the entities in order to make a proper inner join.

Here you can find some examples about that, I also highly recommend you to get LinqPad, its a really valuable tool for testing your queries, also its very good to learn, it has 200+ examples.

Upvotes: 1

Related Questions