0

听起来有点复杂,但这是我想要做的:

我将MyObjectin的某些属性过滤List<MyObject>到一个新的 LINQ 对象中:

 var filteredMyObjects = from r in myObjects select new { r.ComponentName, r.Group, r.Key };

现在的问题是 Properties ComponentNameGroup并且Key应该作为输入(例如List<string>属性名称)。这在我的逻辑中用于将数据导出到 excel 中。

我一直在尝试将它与这个想法结合起来:

typeof(MyObject).GetProperty(property).GetValue(objectInstance) as string

但是我无法理解如何实现它。

编辑:

请参阅我需要实现的示例:

List<string> userDefinedPropeties = new List<string> {Property1, Property2, Property3 ... }

var filteredMyObjects = from r in myObjects select new { r.Property1, r.Property2, r.Property3 ... };

理想的答案看起来像这样,除了这个解决方案在我的情况下不起作用: Linq access property by variable

4

2 回答 2

1

您不能为此使用匿名对象,最好的办法是使用 expando 对象

//List<string> userDefinedPropeties is a parameter
List<dynamic> filteredMyObjects = new List<dynamic>();
foreach (var i in filteredMyObjects)
{

    dynamic adding = new ExpandoObject();
    foreach (var prop in userDefinedPropeties) 
    {
        adding[prop] = i.GetType().GetProperty(prop).GetValue(i);
    }

    filteredMyObjects.Add(adding);

}

// all of the elements of the filtered list can be accessed by using 
// item.`PropertyName`

表达您的问题的更好方法是说您要传递一个仅包含用户请求的属性的对象,不确定为什么 UI 无法处理比请求更多的属性,但您已经解释了你无法控制设计

于 2015-07-10T13:18:29.487 回答
0

您可以使用以下方法伪造动态属性Dictionary

public class CustomObject
{
    Dictionary<string, object> _properties = new Dictionary<string, object>();

    public CustomObject(dynamic parentObject, List<string> properties)
    {
        foreach (string propertyName in properties)
            _properties[propertyName] = parentObject.GetType().GetProperty(propertyName).GetValue(parentObject, null);
    }

    public object this[string name]
    {
        get
        {
            if (_properties.ContainsKey(name))
            {
                return _properties[name];
            }
            return null;
        }
        set
        {
            _properties[name] = value;
        }
    }
}

使用示例:

var myObjects = new List<MyObject>()
{
    new MyObject(1, "Component1", 1, 1),
    new MyObject(2, "Component2", 2, 2),
    new MyObject(3, "Component3", 3, 3),
    new MyObject(4, "Component4", 4, 4),
    new MyObject(5, "Component5", 5, 5),
    new MyObject(6, "Component6", 6, 6),
    new MyObject(7, "Component7", 7, 7),
    new MyObject(8, "Component8", 8, 8),
};

var properties = new List<string>()
{
    "ComponentName", "Group", "Key"
};

List<CustomObject> myCustomObjects = new List<CustomObject>();
foreach (MyObject myObject in myObjects)
    myCustomObjects.Add(new CustomObject(myObject, properties));
于 2015-07-10T13:27:02.817 回答