2015-05-09 234 views
1

我有一個具有大量屬性的對象模型。這些屬性的值是從數據庫中提取,得到IEnumerable列表或數組像這樣:將IEnumerable對象列表轉換爲對象數組列表C#

var obj = context.Model.Where(x => idList.Contains(x.Id)).ToList(); 

這給出了在該結構中一個JSON輸出斑點:

[{ Prop1: 57, Prop2: 2, Prop3: 25 ... }, 
{ Prop1: 23, Prop2: 4, Prop3: 20 ....}, 
{ Prop1: 15, Prop2: 6, Prop3: 32 ....}, 
... ] 

是否有一種方法可以設置LINQ查詢以這種形式來提取數據:

{ Prop1: [57,23,15, ...], 
    Prop2: [2,4,6, ....], 
    Prop3: [25,20,32, ...], 
    ... } 

換句話說欲對象陣列的集合不是對象

0的數組
+0

什麼context.Model.Where(x => idList.Contains(x.Id))。ToArray();給你? –

+0

是的,我們需要關於模型類 –

+0

的詳細信息,Fabian和dbc都有這個要點。更好的是,他們的解決方案都處理一般對象結構和可空類型。 – Xcheque

回答

2

如果您正在使用Json.NET,您可以用LINQ to JSON重組的JSON在一個完全通用的方式,而不需要編寫自己的反射代碼:

 var jArray = JArray.FromObject(obj); // obj must serialized to an array; throw an exception otherwise. 
     var jObj = new JObject(jArray   // Allocate new outer JSON object 
      .Cast<JObject>()     // All array element must be json objects 
      .SelectMany(o => o.Properties()) 
      .GroupBy(p => p.Name, p => p.Value) // Group all array element properties by name 
      .Select(g => new JProperty(g.Key, g))); // Add an array-valued property to the new outer object. 
     var json = jObj.ToString(); 
     Debug.WriteLine(json); 

鑑於以下輸入obj

 var obj = new List<object> 
     { 
      new { Prop1 = 57, Prop2 = 2, Prop3 = 25 }, 
      new { Prop1 = 23, Prop2 = 4, Prop3 = 20 }, 
      new { Prop1 = 15, Prop2 = 6, Prop3 = 32 }, 
     }; 

以下JSON產生:

{"Prop1":[57,23,15],"Prop2":[2,4,6],"Prop3":[25,20,32]} 

另外,如果您obj是強類型,您可以手動創建用於輸出的中間anonymous type,就像這樣:

 var newObj = new { Prop1 = obj.Select(i => i.Prop1), Prop2 = obj.Select(i => i.Prop2), Prop3 = obj.Select(i => i.Prop3) }; 

然後,給出下面的輸入obj

 var obj = new[] 
     { 
      new [] { 57,2,25 }, 
      new [] { 23,4,20 }, 
      new [] { 15,6,32 }, 
     } 
     .Select(a => new { Prop1 = a[0], Prop2 = a[1], Prop3 = a[2] }); 

的生成相同的JSON。

+0

不錯的代碼 - 謝謝 – Xcheque

1

我不認爲你可以用純粹的Linq做到這一點,如果你想通用。你需要至少使用一些反射來遍歷你的屬性。

下面的代碼應該做喲想要的:

 var list = new List<object> {new { A = 1, B = 2, C = 3}, new {A = 1, B = 1, D = 1}}; 

     var result = new ExpandoObject(); 

     var list1 = list.Aggregate<object, ExpandoObject>(result, (res, a) => 
     { 
      foreach (var prop in a.GetType().GetProperties()) 
      { 
       object val = prop.GetValue(a); 

       var x = res as IDictionary<string, Object>; 
       object o; 
       if (!x.TryGetValue(prop.Name, out o)) 
       { 
        o = new List<object>(); 
        x.Add(prop.Name, o); 
       } 

       ((List<object>)o).Add(val); 
      } 

      return res; 
     }); 

      var inputJson = Newtonsoft.Json.JsonConvert.SerializeObject(list); 

     var outputJson = Newtonsoft.Json.JsonConvert.SerializeObject(list1); 

對於此輸入:[{ 「A」:1, 「B」:2, 「C」:3},{ 「A」: 1,「B」:1,「D」:1}]

它給出以下輸出:{「A」:[1,1],「B」:[2,1],「C」: [3],「D」:[1]}

當然,如果你有強類型的類,你不需要使用反射。您也可以傳遞類類型來自行聚合和寫入映射。

+0

這也工作 - 謝謝Fabian。 dbc爲優雅的linq查詢得到了巧克力 – Xcheque

相關問題