Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF statement inside a LINQ SELECT to include columns

Is it possible to include or exclude column within linq Select?

var numberOfYears = Common.Tool.NumberOfYear;
 var list = users.Select(item => new
        {
            Id = item.Id,
            Name= item.Name,
            City= Item.Address.City.Name,
            STATUS = Item.Status,
            if(numberOfYears == 1)
            {
               Y1 = item.Records.Y1,
            }
            if(numberOfYears == 2)
            {
               Y1 = item.Records.Y1,
               Y2 = item.Records.Y2,
            }
            if(numberOfYears == 3)
            {
               Y1 = item.Records.Y1,
               Y2 = item.Records.Y2,
               Y3 = item.Records.Y3,
            }
        }).ToList();
    }

The idea is that i want to display Y1,Y2,Y3 only if has values

like image 661
Maro Avatar asked Sep 13 '16 14:09

Maro


2 Answers

Thanks to the beauty of the dynamic keyword what you need is now possible in C#. Below an example:

public class MyItem
{
    public string Name { get; set; }
    public int Id { get; set; }
}

static void Main(string[] args)
{
    List<MyItem> items = new List<MyItem>
    {
        new MyItem
        {
            Name ="A",
            Id = 1,
        },
        new MyItem
        {
            Name = "B",
            Id = 2,
        }
    };

    var dynamicItems = items.Select(x => {
        dynamic myValue;
        if (x.Id % 2 == 0)
            myValue = new { Name = x.Name };
        else
            myValue = new { Name = x.Name, Id = x.Id };

        return myValue;
    }).ToList();
}

This will return a list of dynamic objects. One with 1 property and one with 2 properties.

like image 131
PiotrWolkowski Avatar answered Nov 16 '22 21:11

PiotrWolkowski


Try this approach:

var numberOfYears = Common.Tool.NumberOfYear;
var list = users.Select(item => new
    {
        Id = item.Id,
        Name = item.Name,
        City = Item.Address.City.Name,
        STATUS = Item.Status,
        Y1 = numberOfYears > 0 ? item.Records.Y1 : 0,
        Y2 = numberOfYears > 1 ? item.Records.Y2 : 0,
        Y3 = numberOfYears > 2 ? item.Records.Y3 : 0
    }).ToList();

Instead of 0, add your default value or null.

Update: According to your comments, the only option for you is to go dynamic. Here's example with dynamics:

var numberOfYears = 3;
var list = users.Select(x =>
{
    dynamic item = new ExpandoObject();
    item.Id = x.Id;
    item.Name = x.Name;
    item.Status = x.Status;

    var p = item as IDictionary<string, object>;
    var recordsType = x.Records.GetType();
    for (var i = 1; i <= numberOfYears; ++i)
        p["Y" + i] = recordsType.GetProperty("Y" + i).GetValue(x.Records);

    return item;
}).ToList();
like image 30
rpeshkov Avatar answered Nov 16 '22 20:11

rpeshkov