How to yield multiple objects with respect to a multi-valued column in Dynamic Linq

c# dynamic-linq json linq


Scenario: I have to export an excel file which will contain list of Parts. We have enabled the user to select the columns and get only selected columns' data in the exported file. Since this is a dynamic report, I am not using any concrete class to map the report as this will result in exporting empty column headers in the report, which is unnecessary. I am using Dynamic Linq to deal with this scenario.

I have a list of dynamic objects fetched from dynamic linq.


How can I get 4 rows out of this json like

enter image description here

Please note that I cannot use a strongly typed object to deserialize/ Map it using JSON.Net

Update Following is the code:

 public class Part
        public int Id { get; set; }
        public string CleanPartNo { get; set; }
        public string Description { get; set; }
        public List<PartAlias> AliasPartNo { get; set; }

public class PartAlias
        public int PartId { get; set; }
        public int PartAliasId { get; set; }
        public string AliasPartNo { get; set; }

var aliases = new List<PartAlias> {
                new PartAlias{AliasPartNo="258" },
                new PartAlias{AliasPartNo="145" },
                new PartAlias{AliasPartNo="2313" },
                new PartAlias{AliasPartNo="12322" }
List<Part> results = new List<Part> {
                new Part{CleanPartNo="Test", Description= "test", PartAlias=aliases  },
                new Part{CleanPartNo="Test1", Description= "test1" }


var filters = "CleanPartNo,Description, PartAlias.Select(AliasPartNo) as AliasPartNo";
var dynamicObject = JsonConvert.SerializeObject(results.AsQueryable().Select($"new ({filters})"));

in the dynamicObject variable I get the json mentioned above

1/29/2019 12:35:24 PM

Popular Answer

From json you provided you can get values grouped by their name in this way:

var array = JArray.Parse(json);
var lookup = array.SelectMany(x => x.Children<JProperty>()).ToLookup(x => x.Name, x => x.Value);

then this is just a manner of simple loop over the lookup to fill the excel columns.

However, I would suggest to do the flatenning before JSON. I tried for some time to make it happen even without knowing the names of the columns that are arrays, but I failed, and since it's your job, I won't try anymore :P

I think the best way here would be to implement custom converter that would just multiply objects for properties that are arrays. If you do it well, you would get infinite levels completely for free.

1/29/2019 3:02:07 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow