2017-05-07 30 views
0

是否可以使用動態LINQ和ExpandoObject執行GroupBy?動態LINQ - 帶有ExpandoObject的Groupby導致錯誤:無適用索引器

考慮下面的例子;理想情況下,我想要一個ExpandoObjects的分組列表。

謝謝你的時間。

var listOfExpandoObjects = new List<ExpandoObject>(); 
var expandoObject = new ExpandoObject(); 
((IDictionary<string, object>)expandoObject).Add("DynamicProperty", "RepeatedItem"); 
((IDictionary<string, object>)expandoObject).Add("OtherProperty", "First"); 
listOfExpandoObjects.Add(expandoObject); 

expandoObject = new ExpandoObject(); 
((IDictionary<string, object>)expandoObject).Add("DynamicProperty", "RepeatedItem"); 
((IDictionary<string, object>)expandoObject).Add("OtherProperty", "Second"); 
listOfExpandoObjects.Add(expandoObject); 

var dynamicGroupBy = "new (it[\"DynamicProperty\"])"; 
var groupedItems = listOfExpandoObjects.GroupBy(dynamicGroupBy, "it"); // <------- Error: 'No applicable indexer exists in type 'ExpandoObject'' 

回答

0

我想你想是這樣的

dynamic expandoObject = new ExpandoObject(); 
expandoObject.DynamicProperty = " RepeatedItem"; 
expandoObject.OtherProperty = "First"; 

dynamic secondExpandoObject = new ExpandoObject(); 
secondExpandoObject.DynamicProperty = "RepeatedItem"; 
secondExpandoObject.OtherProperty = "Second"; 

var listOfExpandoObjects = new List<dynamic> { expandoObject, secondExpandoObject }; 

var dynamicProperty = "DynamicProperty"; 

var groupedItems = 
    from IDictionary<string, object> expando in listOfExpandoObjects 
    group expando by expando[dynamicProperty];