6

我有一个通用<> 函数,它接受一个 linq 查询('items')并通过它枚举添加额外的属性。如何选择原始“项目”的所有属性而不是项目本身(如下面的代码)?

所以等价于sql: select *, 'bar' as 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);
}
4

5 回答 5

5

没有简单的方法可以按照您的建议进行操作,因为 C# 中的所有类型都是强类型的,即使是您正在使用的匿名类型也是如此。不过,也不是不可能做到的。为此,您必须利用反射并在内存中发出您自己的程序集,添加一个包含您想要的特定属性的新模块和类型。可以使用以下方法从您的匿名项目中获取属性列表:

foreach(PropertyInfo info in item.GetType().GetProperties())
    Console.WriteLine("{0} = {1}", info.Name, info.GetValue(item, null));
于 2008-09-21T01:55:54.667 回答
3

射击你写的正是我要发布的内容。我刚刚准备好一些代码:/

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

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 };
});
于 2008-09-21T01:59:47.437 回答
0
from item in items
where someConditionOnItem
select
{
     propertyOne,
     propertyTwo
};
于 2008-09-21T01:41:34.033 回答
0

要求物品将它们交给您。

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

这是一些示例方法签名:

public XElement ToXElement()
public IEnumerable ToPropertyEnumerable()
public Dictionary<string, object> ToNameValuePairs()
于 2008-09-21T03:04:01.010 回答
0

假设您有一个 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" };
于 2014-09-19T06:25:41.647 回答