Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

?: Operator in LINQ Query

  • How do I utilize a ?: operator in the SELECT clause of a LINQ query? If this can't be done, how can I emulate one? The goal is to get a CASE block in my select clause. As you might suspect, I'm getting an error: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

  • Is this the proper way, or a sufficient way, to say "from a inner join i on a.ipid=i.id inner join u on i.uid=u.id"? If not, please provide one. Thanks.

    var query =
        from a in db.tblActivities
        from i in db.tblIPs
        from u in db.tblUsers 
        select new {
            u.UserName == null
                ? i.Address
                : u.UserName,
            a.Request,
            a.DateTime };
    
like image 717
tsilb Avatar asked Nov 12 '08 02:11

tsilb


2 Answers

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.

like image 102
GalacticCowboy Avatar answered Nov 12 '22 16:11

GalacticCowboy


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.

like image 20
Christian C. Salvadó Avatar answered Nov 12 '22 17:11

Christian C. Salvadó