繁体   English   中英

linq相当于'select *'sql的泛型函数?

[英]linq equivalent of 'select *' sql for generic function?

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

所以相当于sql:select *,'bar'作为项目的Foo

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM