is it possible to have a conditional field in an anonymous type(是否可以在匿名类型中有条件字段)
问题描述
我有一些看起来像这样的代码并从现有集合中创建一个列表
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:
- 如果我有 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.
这篇关于是否可以在匿名类型中有条件字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在匿名类型中有条件字段
基础教程推荐
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
