Bryan Bryan - 1 year ago 165
C# Question

Remove empty properties from object in list, c#

I have the following code:

var result = dataService.ItemGeneralSearch_v1("ddd", value[0], value[0]);

var newList = result.Where(x => x.GetType().GetProperties()
.Select(p => p.GetValue(x, null))
.Any(p => p != null)).ToList();


The result contains a List with ItemGeneral-object.

ItemGeneral

public class ItemGeneral
{
public string ITEM_NO { get; set; }
public string ITEM_TYPE { get; set; }
public string ITEM_STATE { get; set; }
public string ITEM_NAME { get; set; }
public string PRODNAME_NO { get; set; }
public string PRODNAME_NO2 { get; set; }
}


The thing Im trying to accomplish is to filter out all the properties that has a null-value in the ItemGeneral-objects. But It don't work with the code above.

Anyone who can help me? I want to return a filtered list with the objects containing only the properties with a value. So no properties with null-values.

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download