是否可以在匿名类型中有条件字段 [英] is it possible to have a conditional field in an anonymous type

查看:36
本文介绍了是否可以在匿名类型中有条件字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些看起来像这样的代码并从现有集合中创建一个列表

i have some code that looks like this and creates a list from an existing collection

 var items = items.ConvertAll(r => new
            {
                description = FormatDescription(r),
                start = r.Milestone.HasValue ? r.Milestone.Value.ToString("yyyy-MM-ddTHH:mm:ssZ") : DateTime.Today.ToString("yyyy-MM-ddTHH:mm:ssZ"),
                classname = "significance" + r.SignificanceLevel,

如您所见,如果我现在没有开始日期 (r.Milestone),那么我输入今天的日期.如果说我真正想做的事:

As you can see, right now if i dont have a start date (r.Milestone) then i put in today's date. What i really want to do if say:

  1. 如果我有 r.Milestone.Hasvalue 显示该日期,如果我没有值,则在匿名类型中根本没有开始日期字段.

是否有可能有这种条件逻辑,您可以在这种类型的代码中一起删除字段?

Is it possible to have this conditional logic where you can remove the field all together inside this type of code?

推荐答案

不,你不能,主要是因为它会使匿名类在不同的执行中有所不同,并且无法对类进行类型检查.

No, you can't, mostly since it would make the anonymous class different in different executions and the class couldn't be type checked.

我建议将您的开始日期设置为 null 而不是默认值,并稍后在您的代码中进行检查.

I'd recommend setting your Start date to null instead of a default, and checking for that later in your code.

这篇关于是否可以在匿名类型中有条件字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆