IF inside LINQ SELECT to include columns

Is it possible to include or exclude a column inside 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 it matters

+4
source share
2 answers

Thanks to the beauty of the keyword dynamic, what you need is now possible in C #. Below is 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.

+2
source

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 the default value or null.

Update: According to your comments, the only option for you is dynamic. Here is a dynamic example:

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();
+1
source

Source: https://habr.com/ru/post/1654476/


All Articles