加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用条件运算符

发布时间:2020-12-15 23:28:39 所属栏目:百科 来源:网络整理
导读:我的数据库中有一个表,它将地址分为三列: First = The House number and street name NOT NULLMiddle = e.g Business park name or NULL Last = Area name or NULL 第一列将始终具有值,但其他两列可能包含值.我想要实现的是,如果Middle或Last为null,则返回
我的数据库中有一个表,它将地址分为三列:

First = The House number and street name NOT NULL
Middle = e.g Business park name or NULL 
Last = Area name or NULL

第一列将始终具有值,但其他两列可能包含值.我想要实现的是,如果Middle或Last为null,则返回第一列值.如果First或Middle有值,则返回那两个,如果all则返回所有3个.所以我想到使用条件运算符来实现这一点.

我的代码如下:

using (var dbContext = new MyEntities())
{
   return dbContext.User.Select(a => new MyUserDto
   {
      Address = !string.IsNullOrEmpty(a.First + a.Middle + a.Last) ? a.First + a.Middle + a.Last : a.First 
   }).ToList();
}

如果middle不为null,如何更改代码以获取First和Middle的值

或者我应该在MyUserDto中创建单独的属性来表示数据库中的内容?

解决方法

if Middle or Last is null return the First column value If First or Middle have value then return those two and if all then return all 3 of them

如果我从字面上解释你的要求,那就是

Address = a.First + (a.Middle == null || + a.Last == null) ? "" : a.Middle + a.Last;

但这意味着如果Last为null但是Middle不是则忽略Last的值,这看起来很奇怪.我怀疑你只是想要空白字符串来代替任何null

Address = a.First + a.Middle + a.Last;

由于在使用非空字符串(与SQL不同)连接空字符串时,它们被视为.NET中的空字符串.

or should I create separate properties in my MyUserDto to represent what’s in the database?

你当然可以这样做,只需添加一个动态连接的属性.这样,您可以独立设置部件,而无需解析连接的字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读