gpt4 book ai didi

c# - 如何从类的集合中获取类的属性列表

转载 作者:行者123 更新时间:2023-11-30 13:31:59 24 4
gpt4 key购买 nike

我有一个场景,我需要获取类属性的值的集合。

public class Person
{
public string Name { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
}

public class PersonCollection : List<Person>
{
public object[] GetValues(string propertyName)
{
// best way to implement this method?
return null;
}
}

我想避免太多的迭代。任何想法都会有所帮助。

最佳答案

一些 Linq 魔法:

public object[] GetValues(Expression<Func<Person, object>> exp)
{
var function = exp.Compile();
return this.Select(function).ToArray();
}

用法:

// assuming coll in a PersonCollection
var names = coll.GetValues(p => p.Name);

关于c# - 如何从类的集合中获取类的属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16959156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com