?: Operator in LINQ Query

后端 未结 5 2099
时光取名叫无心
时光取名叫无心 2021-02-20 15:20
  • 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 claus

5条回答
  •  你的背包
    2021-02-20 16:24

    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.

提交回复
热议问题