Include conditional properties in anonymous types

Suppose I have the following anonymous type

var g = records.Select(r => new
{                    
    Id = r.CardholderNo,
    TimeIn = r.ArriveTime,
    TimeOut = r.LeaveTime,
});

      

Is it possible to do something like the following:

var g = records.Select(r => new
{                    
    Id = r.CardholderNo,
    if (condition) 
    {
        TimeIn = r.ArriveTime;
    },
    TimeOut = r.LeaveTime,
    //many more properties that I'd like to be dependant on conditions.
});

      

How can I get the anonymous type based on conditions?

+3


source to share


4 answers


Directly using the operator if

, but you can do it with the ternary operator (if it TimeIn

has a type DateTime

):

var g = records.Select(r => new
{

    Id = r.CardholderNo,
    TimeIn = condition ? r.ArriveTime : (DateTime?)null;
    TimeOut = r.LeaveTime
});

      



Note that this property will always appear in your anonymous type. If this is not the desired behavior, then you cannot do it this way.

I would suggest thinking about the readability of your code, not just "how can I shorten these few lines to make it look neat".

+4


source


Not. Anonymous types are like any other type. It has a fixed list of properties. You cannot add or remove properties dynamically.



I suggest either setting a property null

as in the other answers, or using Dictionary

where you add the corresponding properties and their values.

+3


source


You can do this using the thermal operator :?:

The syntax is as follows:

TimeIn = condition ? r.ArriveTime : (DateTime?)null // Or DateTime.Min or whatever value you want to use as default

      

UPDATE

After thinking about your problem for a couple of minutes, I came up with the following code that you should never use;)

using System;

class Program
{
    static void Main(string[] args)
    {
        DateTime dt = DateTime.Now;

        bool condition = true;

        dynamic result = condition ?
            (object)new
            {
                id = 1,
                prop = dt
            }
            :
            (object)new
            {
                id = 2,
            };

        Console.WriteLine(result.id);
        if (condition) Console.WriteLine(result.prop);
    }
}

      

This code should never be used in production due to its terrible readability and this is indeed a bug. However, as an example of learning what is possible with the language, it is quite enjoyable.

+2


source


If you really need if

(or any other operator) to create an anonymous type, you can try this not very acceptable solution:

var g = records.Select(r => new
{
    Id = r.CardholderNo,
    TimeIn = new Func<DateTime?, DateTime?>(x =>
            {
            if (...)
                return x;
            else
                return null;
            }).Invoke(r.ArriveTime),
    TimeOut = r.LeaveTime,
});

      

+1


source







All Articles