jeudi 9 avril 2015

Get some properties from an object and nested object

I'd like return an object (ExpandoObject) with only the fields and nested fields received by the method.



var fieldsToGet = new List<string> { "FirstName", "Id"};


When I do this :



.Select(x => Helpers.FilteringProperties(x, fieldsToGet))


I receive an object with this two values, that's work. I receive an object with FirstName and Id


Now I'd like return some properties of the nested object :



var fieldsToGet = new List<string> { "FirstName", "Id", "Language.Name"};


I'd like receive these properties : FirstName, Id and Language.Name


The code below works but I'd like stay generic enough and be able to manage the nested.


How can I do this generic, managed the nested object ?


Thanks,


The current code :



public static object FilteringProperties(object employee, List<string> fields)
{
if (!fields.Any())
return employee;
else
{
ExpandoObject result = new ExpandoObject();
foreach (var field in fields)
{
var fieldValue = employee.GetType()
.GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance)
.GetValue(employee, null);

((IDictionary<String, Object>)result).Add(field, fieldValue);
}
return result;
}
}


Sample classes :



public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public Language Language { get; set; }
public int LanguageId { get; set; }
}

public class Language
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}





Aucun commentaire:

Enregistrer un commentaire