传递用于在LINQ查询中形成新对象的对象属性列表



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

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

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

现在的问题是属性ComponentName, GroupKey应该作为输入(例如属性名称的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访问属性

不能使用匿名对象,最好使用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不能处理比请求更多的属性,但你已经解释了你不能控制设计

您可以使用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));

相关内容

  • 没有找到相关文章

最新更新