vendredi 11 octobre 2019

C# 7.0 - Enumerate Certain Object Properties using nameof() like function

I have the following piece of code:

var productsQueryable = _productRepository.GetProductsQueryable(filter:productFilter, includeProperties:"Indicators,ProductComputeParams,ProductDetails");

The idea is that I want to query the Products table using Entity framework and I want to include certain relations in the results.

My issue is that I do not want to hardcode the product properties, but have them break at compile time if any changes are made.

I have created a .NET fiddle with my solution but I am searching for something more elegant, like:

Console.Writeline( nameof(p=>{p.Indicators,p.ProductComputeParams,p.ProductDetails}))
// result is Indicators,ProductComputeParams,ProductDetails

The code I have so far uses reflection: .NET Fiddle sample code

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        //Console.WriteLine(nameof(Product.Indicators));
        Product product = new Product();
        Console.WriteLine( NameOfArray(new{ product.Indicators, product.ProductComputeParams, product.ProductDetails }));
        // result is Indicators,ProductComputeParams,ProductDetails
    }

    public static string NameOfArray(object toDisplay)
    {
        List<string> values = new List<string>();
        foreach (var pi in toDisplay.GetType().GetProperties())
        {
            values.Add(pi.Name);
        }

        return string.Join(",", values);
    }
}

public class Product
{
    public object Indicators {get; set;}

    public object ProductComputeParams {get; set;}

    public object ProductDetails {get; set;}

    public object ProductRecallValues {get; set;}
}




Aucun commentaire:

Enregistrer un commentaire