is it possible to have a conditional field in an anonymous type

余生长醉 提交于 2019-12-04 00:29:12

问题


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,

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. if i have a r.Milestone.Hasvalue show that date, if i dont have a value DONT HAVE THE START DATE field in the anonymous type at all.

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


回答1:


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

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



来源:https://stackoverflow.com/questions/3090218/is-it-possible-to-have-a-conditional-field-in-an-anonymous-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!