Suppose we have a simple class called Person
with properties as FirstName, LastName, Age
.
Now I have a list of properties as a list of strings.
var props = new List<string> { "FirstName", "Age"}.
Now I have a List
of Person
objects.
var persons = new List<Person> {....}
How to use Select
LINQ method to get just the Person properties that appear in the props
?
var result = persons.Select(p => code here)
The result should be a list of anonymous objects, where an anonymous object should contain the properties from props
list.
CodePudding user response:
Could you try this:
IEnumerable<string> personProps = typeof(Person).GetProperties().Select(p => p.Name);
List<string> props = new List<string> { "FirstName", "Age"};
IEnumerable<string> selectedProps = props.Where(p => personProps.Contains(p));
CodePudding user response:
If I get your question correctly you want to kind of trim your Person object. If that's correct I'd recommend to create an instance method inside your Person class that gives you the opportunity to create an unnamed object or Tuple (for example like here: C# ValueTuple of any size) directly from your Person instanciated object. You just need to pass your props List for matching the properties (like here: enter link description here) then and just use this very method inside your Select statement.
CodePudding user response:
try this code. It was tested in Visual Studio and works properly
var props = new List<string> { "FirstName", "Age" };
var persons = new List<Person> {
new Person { FirstName = "FirstName1", LastName = "FirstName1", Age=10},
new Person { FirstName = "FirstName2", LastName = "FirstName2", Age=20},
new Person { FirstName = "FirstName3", LastName = "FirstName3", Age=30}
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(persons);
var jArray = JArray.Parse(json);
List<JObject> list = new List<JObject>();
foreach (var item in jArray)
{
JObject jsonObj = new JObject();
foreach (var prop in props)
{
foreach (JProperty jprop in item)
{
if (jprop.Name == prop)
jsonObj.Add(jprop);
}
}
list.Add(jsonObj);
}
json = JsonConvert.SerializeObject(jsonList);
to use it you can convert to dictionary for example
var dictArray = JsonConvert.DeserializeObject<Dictionary<string, object>[]>(json);
or list of tuples or key-value pairs
List<(string,object)> values = dictArray.SelectMany(i=>i).Select(i =>(i.Key,i.Value)).ToList();
output
FirstName FirstName1
Age 10
FirstName FirstName2
Age 20
FirstName FirstName3
Age 30
or you can convert to dynamic object
dynamic eo = dictArray.Select( e=> e.Aggregate(new ExpandoObject() as IDictionary<string, Object>,
(a, p) => { a.Add(p.Key, p.Value); return a; })).ToList();
test
var firstName = eo[1].FirstName; //FirstName2
class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}