Search code examples
c#classreflectioncollectionsdatatable

Get class properties of a specific type


I have a WinForm project in c#. I have class named TopProducts that has many DataTable properties and I create a collection of this class.

I want to loop over this collection and create List<Datatable>. You can find details in the comments in the GetListOfDataTables method below.

public class TopProducts
{
    public Guid ID { get; set; }
    public string No { get; set; }
    public string ProductName { get; set; }
    public int ProductQty { get; set; }
    public int Level { get; set; }
    public DataTable dtProfile { get; set; }
    public DataTable dtPBMAndGlass { get; set; }
    public DataTable dtArticals { get; set; }
    public DataTable dtCutting { get; set; }
    public DataTable dtCNC { get; set; }
    public DataTable dtIFS { get; set; }
    public DataTable dtIFSGlassList { get; set; }   
    // public DataTable MoreDataTable
}

public List<DataTable> GetListOfDataTables(List<TopProducts> ProductList)
{
    List<DataTable> dtList = new List<DataTable>();
    foreach (TopProducts product in ProductList)
    {
        //I need codes something similar below
        //if (product.GetType().Equals(DataTable))
        //{
            // dtList.Add(product) 
        //}
    }
    return dtList;
}

Solution

  • It seems you mean using Reflection to extract the values of the DataTable properties from a given List<TopProducts> and flatten them in one sequence. If so, you could have:

    // +
    using System.Reflection;
    
    public IEnumerable<DataTable> GetListOfDataTables(IEnumerable<TopProducts> ProductList) 
        => ProductList
        .SelectMany(topProduct => topProduct.GetType()
        .GetProperties(BindingFlags.Instance | BindingFlags.Public)
        .Where(propInfo => propInfo.PropertyType == typeof(DataTable))
        .Select(propInfo => propInfo.GetValue(topProduct) as DataTable))
        .Where(dt => dt != null);