Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

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?

like image 866
leora Avatar asked Jun 22 '10 04:06

leora


People also ask

What is the difference between an anonymous type and a regular data type?

From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.

What is an anonymous type in C?

Vincent Diamante (CC BY-SA 2.0) An anonymous type is a type that doesn't have a name. You can use an anonymous type to encapsulate a set of read-only properties inside a single unit — and you don't need to define the anonymous type beforehand.

When can an anonymous type be created?

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .

How do I change my class type to Anonymous?

Convert anonymous type(s) into a named typePress Ctrl+Shift+R and then choose Replace Anonymous Type with Named Class.


1 Answers

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.

like image 150
Will Eddins Avatar answered Sep 20 '22 14:09

Will Eddins