I have a list of properties which will be dynamic and can frequently change on each request.
var dynamicFields = new List<string>{ "UserName", "UserEmail" };
I have an another list of class which contains all dynamicFields and other fields.
var staticFields = new List<StaticFields>
{
new StaticFields {UserName = "Chandra", UserDepartment = "IT", UserCity = "Bangalore", UserEmail = "[email protected]"},
new StaticFields {UserName = "Sekar", UserDepartment = "CSE", UserCity = "Bangalore", UserEmail = "[email protected]"},
new StaticFields {UserName = "Dilip", UserDepartment = "IT", UserCity = "Bangalore", UserEmail = "[email protected]"}
};
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 fields are in dynamicFields list.
So how can I achieve this in C# either using for loops or using LINQ ?
Edit:
Purpose is used to display only selected columns in display. I'm using SP to fetch all the data from DB. It's a legacy code from db, so I don't have any access to change 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 have to convert this code to C#
You can use dynamic LINQ with proper 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 could 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
}
Remarks:
result into JSON without any problems - DynamicClass is built with properties.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With