簡體   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