2015-07-10 62 views
0

聽起來有點複雜,但這裏是我想做的事:合格名單,形成LINQ查詢中一個新的對象

我過濾的MyObject某些屬性在List<MyObject>成新LINQ對象爲:

var filteredMyObjects = from r in myObjects select new { r.ComponentName, r.Group, r.Key }; 

現在的問題是,屬性ComponentNameGroupKey應該來作爲輸入(例如屬性名稱的List<string>)。這在我的邏輯中用於將數據導出到excel中。

我一直在試圖把它與這一理念相結合:

typeof(MyObject).GetProperty(property).GetValue(objectInstance) as string 

但不能換我圍​​繞如何實現它的頭。

編輯:

見例如什麼,我需要實現:

List<string> userDefinedPropeties = new List<string> {Property1, Property2, Property3 ... } 

var filteredMyObjects = from r in myObjects select new { r.Property1, r.Property2, r.Property3 ... }; 

理想的答案是這樣的,但這種解決方案並不在我的情況下工作 : Linq access property by variable

+1

我真的不明白你想要做什麼。你想訪問你選擇的匿名對象的屬性嗎?在那種情況下,爲什麼不創建一個新的類,我猜是一種DTO,它可以讓你選擇新的MyDtoObject {...}? – kai

+0

簡單。我想傳遞哪些屬性在我的filteredMyObjects var中使用。 – eYe

+0

爲什麼不提供一個ListBox供用戶從可用屬性中進行選擇?反思總是容易出錯。 –

回答

1

您不能使用anonymous ob JECT對於這一點,最好的辦法是用在Expando對象

//List<string> userDefinedPropeties is a parameter 
List<dynamic> filteredMyObjects = new List<dynamic>(); 
foreach (var i in filteredMyObjects) 
{ 

    dynamic adding = new ExpandoObject(); 
    foreach (var prop in userDefinedPropeties) 
    { 
     adding[prop] = i.GetType().GetProperty(prop).GetValue(i); 
    } 

    filteredMyObjects.Add(adding); 

} 

// all of the elements of the filtered list can be accessed by using 
// item.`PropertyName` 

也更好地表達你的問題是說,你想傳遞的是隻包含用戶請求的屬性的對象,而不是知道爲什麼UI將不能夠處理比要求更多的屬性,但是你解釋你不擁有控制權的設計

+1

他可能試圖擺脫顯式循環,這在執行導出時會降低很多速度。 – sonne

+0

@sonne OP正在使用linq語句進行迭代,就像循環只是懶惰地評估一樣昂貴 – konkked

+0

@konkked我試過這種方法,並且輸出時間爲〜52秒〜4000條記錄。當我使用ClosedXML文檔中提供的查詢方法時,時間已降至〜500ms。所以不幸的是,這不會工作。 – eYe

0

你可以動態屬性使用Dictionary

public class CustomObject 
{ 
    Dictionary<string, object> _properties = new Dictionary<string, object>(); 

    public CustomObject(dynamic parentObject, List<string> properties) 
    { 
     foreach (string propertyName in properties) 
      _properties[propertyName] = parentObject.GetType().GetProperty(propertyName).GetValue(parentObject, null); 
    } 

    public object this[string name] 
    { 
     get 
     { 
      if (_properties.ContainsKey(name)) 
      { 
       return _properties[name]; 
      } 
      return null; 
     } 
     set 
     { 
      _properties[name] = value; 
     } 
    } 
} 

使用例如:

var myObjects = new List<MyObject>() 
{ 
    new MyObject(1, "Component1", 1, 1), 
    new MyObject(2, "Component2", 2, 2), 
    new MyObject(3, "Component3", 3, 3), 
    new MyObject(4, "Component4", 4, 4), 
    new MyObject(5, "Component5", 5, 5), 
    new MyObject(6, "Component6", 6, 6), 
    new MyObject(7, "Component7", 7, 7), 
    new MyObject(8, "Component8", 8, 8), 
}; 

var properties = new List<string>() 
{ 
    "ComponentName", "Group", "Key" 
}; 

List<CustomObject> myCustomObjects = new List<CustomObject>(); 
foreach (MyObject myObject in myObjects) 
    myCustomObjects.Add(new CustomObject(myObject, properties));