我有一个通用<!> lt; <!> gt;获取linq查询('items')的函数,并通过它枚举添加其他属性。如何选择原始“项目”的所有属性而不是项目本身(如下面的代码所示)?

等同于sql:select *,'bar'作为Foo from items

foreach (var item in items)
{
    var newItem = new {
        item, // I'd like just the properties here, not the 'item' object!
        Foo = "bar"
    };

    newItems.Add(newItem);
}
有帮助吗?

解决方案

没有简单的方法来做你所建议的事情,因为C#中的所有类型都是强类型的,甚至像你正在使用的匿名类型。然而,将它拉下来并非不可能。要做到这一点,你必须利用反射并在内存中发出自己的程序集,添加一个包含所需特定属性的新模块和类型。您可以使用以下方式从匿名项目中获取属性列表:

foreach(PropertyInfo info in item.GetType().GetProperties())
    Console.WriteLine("{0} = {1}", info.Name, info.GetValue(item, null));

其他提示

拍你准确写了我要发布的内容。我只是准备了一些代码:/

它有点令人费解,但无论如何:

ClientCollection coll = new ClientCollection();
var results = coll.Select(c =>
{
    Dictionary<string, object> objlist = new Dictionary<string, object>();
    foreach (PropertyInfo pi in c.GetType().GetProperties())
    {
        objlist.Add(pi.Name, pi.GetValue(c, null));
    }
    return new { someproperty = 1, propertyValues = objlist };
});
from item in items
where someConditionOnItem
select
{
     propertyOne,
     propertyTwo
};

要求该项目给你。

反射是一种方式......但是,由于所有属性在编译时都是已知的,因此每个项目都可以有一个方法来帮助此查询获得所需的内容。

以下是一些示例方法签名:

public XElement ToXElement()
public IEnumerable ToPropertyEnumerable()
public Dictionary<string, object> ToNameValuePairs()

假设您有一个Department类的集合:

   public int DepartmentId { get; set; }
   public string DepartmentName { get; set; }

然后使用这样的匿名类型:

        List<DepartMent> depList = new List<DepartMent>();
        depList.Add(new DepartMent { DepartmentId = 1, DepartmentName = "Finance" });
        depList.Add(new DepartMent { DepartmentId = 2, DepartmentName = "HR" });
        depList.Add(new DepartMent { DepartmentId = 3, DepartmentName = "IT" });
        depList.Add(new DepartMent { DepartmentId = 4, DepartmentName = "Admin" });
        var result = from b in depList
                     select new {Id=b.DepartmentId,Damartment=b.DepartmentName,Foo="bar" };
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top