LINQ相当于"选择*"的SQL通用功能?

时间:2020-03-06 14:29:52  来源:igfitidea点击:

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

因此等效于sql:从项目中选择*,'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);
}

解决方案

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

没有任何简单的方法可以执行建议,因为Care中的所有类型都是强类型,甚至是我们正在使用的匿名类型。但是,并非不可能。为此,我们将必须利用反射并在内存中发出自己的程序集,添加一个新模块和包含所需特定属性的类型。可以使用以下方法从匿名项目中获取属性列表:

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

要求物品给他们。

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

这是一些方法签名示例:

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