Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include properties based on conditions in anonymous types

Supposing 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 achieve an anonymous type based on conditions?

like image 418
Null Reference Avatar asked Dec 14 '22 17:12

Null Reference


1 Answers

You can do this by using the ternary operator: ?:

The syntax is like this:

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 ever 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 because of it's terrible readability and it's really error prone. However, as a learning example of what's possible with the language it's quite nice.

like image 88
Wouter de Kort Avatar answered Dec 17 '22 05:12

Wouter de Kort