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

3

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

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;
    }
}

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

7个回答

4
一些 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);

2
一种简单的解决方案是使用LINQ的Select方法:
using System;
using System.Collections.Generic;
using System.Linq;

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)
    {
        if (propertyName == "Name")
        {
            return this.Select(p => p.Name).ToArray();
        }
        else if (propertyName == "Property1")
        {
            return this.Select(p => p.Property1).ToArray();
        }
        else if (propertyName == "Property2")
        {
            return this.Select(p => p.Property1).ToArray();
        }

        // best way to implement this method?
        return null;
    }
}

您也可以使用表达式树来允许使用类型安全的访问器 lambda 作为参数:
public object[] GetValues(Expression<Func<Person, object>> propertyNameExpression)
{
    var compiledPropertyNameExpression = propertyNameExpression.Compile();

    if (propertyNameExpression.Body.NodeType == ExpressionType.MemberAccess)
    {
        return this.Select(compiledPropertyNameExpression).ToArray();
    }

    throw new InvalidOperationException("Invalid lambda specified. The lambda should select a property.");
}

您可以按照以下方式使用此功能:
var personNames = personCollection.GetValues(p => p.Name)

2
一个不使用反射的简单想法是这样的:
public partial class PersonCollection: List<Person> {
    public object[] GetValues(String propertyName) {
        return (
            from it in this
            let x=
                "Name"==propertyName
                    ?it.Name
                    :"Property1"==propertyName
                        ?it.Property1
                        :"Property2"==propertyName
                            ?it.Property2
                            :default(object)
            where null!=x
            select x).ToArray();
    }
}

但是我更愿意返回一个 IEnumerable,以免急切地枚举:

public partial class PersonCollection: List<Person> {
    public IEnumerable GetValues(String propertyName) {
        return
            from it in this
            let x=
                "Name"==propertyName
                    ?it.Name
                    :"Property1"==propertyName
                        ?it.Property1
                        :"Property2"==propertyName
                            ?it.Property2
                            :default(object)
            where null!=x
            select x;
    }
}

1

try this,

public object[] GetValues(string propertyName)
{
    List<object> result = new List<object>();
    PropertyInfo propertyInfo = typeof(Person).GetProperty(propertyName);
    this.ForEach(person => result.Add(propertyInfo.GetValue(person)));
    return result.ToArray();
}

1
这是一个可运行的程序。
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)
    {
        var result = new List<object>();
        foreach (Person item in this)
        {
            result.Add(item.GetType().GetProperty(propertyName).GetValue(item));
        }
        return result.ToArray();
    }
}
class Program
{
    static void Main(string[] args)
    {
        var collection = new PersonCollection();
        collection.Add(new Person(){Name = "George", Property1 = "aaa", Property2 = "bbbb"});
        collection.Add(new Person(){Name = "Peter", Property1 = "ccc", Property2 = "dddd"});
        var objects = collection.GetValues("Property1");
        foreach (object item in objects)
        {
            Console.WriteLine(item.ToString());
        }
        Console.Read();
    }
}

1

使用反射

Person P = new Person(); object obj = p.GetType().GetProperty(propertyName).GetValue(p, null);


0
如果您正在使用实体框架, 您可以使用this.GetAll();

很遗憾,我没有使用那个。 - D J

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接