【问题标题】:linq equivalent of 'select *' sql for generic function?linq 等效于通用函数的'select *' sql?
【发布时间】:2010-09-11 17:11:11
【问题描述】:

我有一个通用的 函数,它接受一个 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);
}

【问题讨论】:

    标签: c# linq generics anonymous-types


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      这有点复杂,但无论如何:

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

      【讨论】:

      • 我重新编辑了代码以取出一个毫无意义的内部选择
      • 只是为了解释一下,这就是之前发布的内容,它将属性添加到新生成项目的列表中。这确实是自动拥有所有值的唯一方法。
      【解决方案3】:
      from item in items
      where someConditionOnItem
      select
      {
           propertyOne,
           propertyTwo
      };
      

      【讨论】:

      • 谢谢,但属性不能硬编码,因为 'item' 是通用函数中的匿名类型
      【解决方案4】:

      请物品交给你。

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

      这是一些示例方法签名:

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

      【讨论】:

        【解决方案5】:

        假设你有一个 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" };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-27
          • 2022-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-14
          相关资源
          最近更新 更多