Linq Select list of dynamic properties to another object?

I have a list of properties that will be dynamic and may change frequently on every request.

var dynamicFields = new List<string>{ "UserName", "UserEmail" }; 

      

I have another list of classes that contains all dynamicFields and other fields.

var staticFields = new List<StaticFields>
    {
        new StaticFields {UserName = "Chandra", UserDepartment = "IT", UserCity = "Bangalore", UserEmail = "abc@gmail.com"},
        new StaticFields {UserName = "Sekar", UserDepartment = "CSE", UserCity = "Bangalore", UserEmail = "xyz@gmail.com"},
        new StaticFields {UserName = "Dilip", UserDepartment = "IT", UserCity = "Bangalore", UserEmail = "cba@gmail.com"}
    };

public class StaticFields
{
    public string UserName {get; set;}
    public string UserDepartment {get; set;}
    public string UserCity {get; set;}
    public string UserEmail {get; set;}
    //etc..
}

      

-

I have to select only the fields in the dynamicFields list.

So how can I achieve this in C # using for for loops or using LINQ?

Edit:

The assignment is used to display only selected columns on the display. I am using SP to fetch all data from DB. This is legacy code from db, so I don't have access to DB stored procedures.

I have tried below code in JS.

var i;
var properties = [
 'UserName',
 'UserEmail'
];
for (i = 0; i < properties.length; i += 1) {
 document.writeln(properties[i] + ': ' + another_object[properties[i]]);
}

      

I need to convert this code to C #

+3


source to share


1 answer


You can use dynamic LINQ with the appropriate extensions:

public static T GetValue<T>(this DynamicClass dynamicObject, string propName)
{
    if (dynamicObject == null)
    {
        throw new ArgumentNullException("dynamicObject");
    }

    var type = dynamicObject.GetType();
    var props = type.GetProperties(BindingFlags.Public 
                                 | BindingFlags.Instance 
                                 | BindingFlags.FlattenHierarchy);
    var prop = props.FirstOrDefault(property => property.Name == propName);
    if (prop == null)
    {
        throw new InvalidOperationException("Specified property doesn't exist.");
    }

    return (T)prop.GetValue(dynamicObject, null);
}

public static string ToDynamicSelector(this IList<string> propNames)
{
   if (!propNames.Any()) 
       throw new ArgumentException("You need supply at least one property");
   return string.Format("new({0})", string.Join(",", propNames));
}

      

Then you can use it like this:



using System.Linq.Dynamic;
...

var result = staticFields.AsQueryable().Select(dynamicFields.ToDynamicSelector())
                                       .Cast<DynamicClass>();

foreach (var item in result)
{
    Console.WriteLine(item.GetValue<string>(list[0]); // outputs all user names
}

      

Notes:

  • Dynamic LINQ supports EF, so you can fetch data directly from DB
  • You can serialize result

    to JSON without issue - DynamicClass

    generated with properties.
+5


source







All Articles