簡體   English   中英

將IEnumerable對象列表轉換為對象數組列表C#

[英]Convert IEnumerable object list to list of object arrays C#

我有一個具有大量屬性的對象模型。 從數據庫中提取這些屬性的值以提供IEnumerable列表或數組,如下所示:

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

這給出了這個結構中的Json輸出blob:

[{ 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, ...],
  ... }

換句話說,我希望對象數組的集合不是對象數組

如果您使用的是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是強類型的,你可以手動為輸出創建一個中間匿名類型 ,如下所示:

        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。

如果你想成為通用的話,我認為你不能用純粹的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]}

當然,如果您有強類型類,則不需要使用反射。 您還可以傳遞類類型以自行聚合和編寫映射。

轉換列表<string>列出<object>在 C#<div id="text_translate"><p> 我有一個看起來像這樣的字符串列表:</p><pre> var rawData = new List<string>(){ "EUR/USD;123", "EUR/GBP;321", "BTC/USD;2321"};</pre><p> 我有以下結構:</p><pre> public class Data { public string instrument { get; set; } public string positions { get; set; } }</pre><p> 我的目標是有一個字符串數據列表,在';'上分開 char 並轉換為對象列表。</p><pre> var processedData = new List<Data>(); // processedData[0] ( instrument = EUR/USD, positions = 123 ) // processedData[1] ( instrument = EUR/GBP, positions = 321) // processedData[2] ( instrument = BTC/USD, positions = 2321)</pre><p> 你知道我該怎么做嗎?</p></div></object></string>

[英]Convert List<string> to List<object> in C#

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM