通用函数的LINQ等效于SQL中的“SELECT *”是什么?

6
我有一个通用的函数,它接受一个 Linq 查询 ('items') 并枚举它,添加额外的属性。如何选择原始 'item' 的所有属性而不是 item 本身呢(就像下面的代码所做的那样)?
所以等同于 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);
}
5个回答

5

您所提出的要求并不容易实现,因为在C#中所有类型都是强类型的,即使是您正在使用的匿名类型也是如此。但是这并非不可能实现。要实现它,您需要利用反射并在内存中发出自己的程序集,添加一个新模块和包含所需特定属性的类型。可以使用以下方法从匿名项中获取属性列表:

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

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

我重新编辑了代码,去除了一个无意义的内部查询。 - mattlant
只是为了解释,这个程序做的是之前发布的内容,它将属性添加到您新生成的项目列表中。这确实是自动拥有所有值的唯一方法。 - mattlant

0
from item in items
where someConditionOnItem
select
{
     propertyOne,
     propertyTwo
};

谢谢,但是在一个泛型函数中“item”是一个匿名类型,属性不能硬编码。 - Nick

0

请请求该项将它们交给您。

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

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

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

0
假设你有一个部门类的集合:
   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" };

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