2010-11-10 34 views
0

我有一個層次集合對象,我試圖在Linq中檢索最後一級對象的屬性。我不想爲每個屬性寫一個get方法。不知道如何通過選擇器來實現它Linq中的通用屬性獲取器

Class Test { 
    public int ID { get; set; } 
    public int PopertyA { get; set; } 
    public string PopertyB { get; set; } 
       ...Many more properties 

} 

public static TResult GetTest(hierarchyObject, int ID, Func<TSource, TResult> selector) 
{ 
    return (from level1 in hierarchyObject.Level1 
      from test in level1.Test 
      where test.ID.Equals(ID) 
      select selector).First(); 
} 

這個工作。目前我已經使方法返回測試對象並訪問調用方法中的屬性。但是想知道我是否可以實現一個通用屬性獲取器。

編輯:

Class Hierarcy{ 
    public IList<Level1> level1; 
} 

Class Level1 { 
public IList<Test> test; 
} 

給定一個層次結構對象並test.ID,我想要檢索測試的任何財產。

+3

我已經通過5次讀這一點,還是不明白,你要怎麼辦... – cjk 2010-11-10 07:57:16

+0

你沒有提供足夠的細節。你的「層級」是如何組織的? 'Level1'的類型是什麼?如果有一個名爲'Level2'或'Level3'的子屬性,那是什麼類型? 「最後一關」是什麼意思? – Groo 2010-11-10 08:01:19

+0

hierarchyObject具有Level1的集合,它具有Test的集合 – anivas 2010-11-10 09:20:51

回答

1

這取決於你想用你的財產做什麼。爲了避免重複對你有興趣,倒不如先得到測試對象,然後檢查其個別屬性的每一個屬性整個LINQ查詢:

class Hierarcy 
{ 
    public IList<Level1> Level1; 
    public Test GetTest(int ID) 
    { 
     return this 
      .Level1 
      .SelectMany(level => level.Test) 
      .Where(test => test.ID == ID) 
      .First(); 
    } 
} 

一旦你得到了Test類,你有它的所有屬性:

Test t = myHierarchy.GetTest(someId); 

// this will print all properties and their values 
foreach (PropertyInfo pi in t.GetType().GetProperties()) 
{ 
    Console.WriteLine("Name:{0}, Value:{1}", 
     pi.Name, 
     pi.GetValue(pi, null)); 
} 

Test t = myHierarchy.GetTest(someId); 

// do something 
int i = test.PropertyA; 
string s = text.PropertyB; 

如果你有興趣在獲取屬性的值動態,只使用其名稱,你可以使用反射做10

在這兩個示例中,實際查詢只執行一次,如果集合中有很多對象,則這可能很重要。

0

您必須使用方法鏈。你不能使用查詢表達式。至少對於選擇部分。 Rest可以保持爲查詢表達式。

hiearchyObject.Level1.SelectMany(x=>x.Test).Where(test=>test.ID.Equals(ID)).Select(selector).First(); 

現在沒有PC來測試它。

另外,在方法,您應該宣佈整個方法的通用acording來選擇(相同的通用參數),或使用public static TResult GetTest<TResult> (.. , Func<Test, TResult> selector)

+1

他不能只是'選擇選擇器(測試)'? – CodesInChaos 2010-11-10 08:45:07

+0

因爲在你的情況下,它會創建新的方法,它只是簡單地調用選擇器方法。在我的情況下,你正在直接使用選擇器方法調用。 – Euphoric 2010-11-10 12:19:05

1

我猜你可能想是這樣的:

public static TResult GetTest(hierarchyObject, int ID, Func<Test, TResult> selector) 
{ 
    return (from level1 in hierarchyObject.Level1 
      from test in level1.Test 
      where test.ID.Equals(ID) 
      select selector(test)).First(); 
} 
相關問題