[Solved] Remove empty properties from object in list in C#


You cannot achieve this if you want to stay with your custom type. Reason is that if you define a type with some properties then when initializing that type the properties are there, whether you assign to them a value or not.

However using anonymous types and dynamic you can:

var result = data.Select(item => {
        dynamic expando = new ExpandoObject();
        var x = expando as IDictionary<string, object>;
        foreach (var p in item.GetType().GetProperties().Where(p => p.GetValue(item) != null))
            x[p.Name] = p.GetValue(item, null);
        return expando;
    }).ToList();

solved Remove empty properties from object in list in C#