I have below class structure,
public class CollectionProperty
{
public string Name { get; set; }
public object Value { get; set; }
public string DataType { get; set; }
}
public class Instance
{
public string Name { get; set; }
public List<CollectionProperty> CollectionProperties { get; set; }
}
public class CollectionResult
{
public string Asset { get; set; }
public List<Instance> Instances { get; set; }
}
I have below collection result with 2 instance having various collection property with 2 data types double and string.
var collectionResult = new CollectionResult
{
Asset = "A1",
Instances = new List<Instance>
{
new Instance
{
Name = "Instance-1",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "N1", Value = 10, DataType = "Double"},
new CollectionProperty {Name = "N2", Value = "S1", DataType = "String"}
}
},
new Instance
{
Name = "Instance-2",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "N1", Value = 20, DataType = "Double"},
new CollectionProperty {Name = "N2", Value = "S2", DataType = "String"}
}
}
}
};
Now my goal to split the collection result various instance and group them based on data type. With below code I am able to split put but it's giving me 4 collection results, but it's should give 2 (2 for double and 2 for string), please suggest. Thanks!

var X = collectionResult.Instances
.SelectMany(collectionInstance => collectionInstance.CollectionProperties,
(collectionInstance, collectionProperty) =>
new
{
CollectionResult = new CollectionResult
{
Asset = collectionResult.Asset,
Instances = new List<Instance>
{
new Instance
{
Name = collectionInstance.Name,
CollectionProperties = new List<CollectionProperty>
{
collectionProperty
}
}
},
},
Instance = collectionInstance.Name,
Property = collectionProperty.Name,
DataType = collectionProperty.DataType
});
You just need to simply add a GroupBy statement after your selectMany:
var X = collectionResult.Instances
.SelectMany(collectionInstance => collectionInstance.CollectionProperties,
(collectionInstance, collectionProperty) =>
new
{
CollectionResult = new CollectionResult
{
Asset = collectionResult.Asset,
Instances = new List<Instance>
{
new Instance
{
Name = collectionInstance.Name,
CollectionProperties = new List<CollectionProperty>
{
collectionProperty
}
}
},
},
Instance = collectionInstance.Name,
Property = collectionProperty.Name,
DataType = collectionProperty.DataType
}).GroupBy(c => c.DataType);
In this way you will have two groups, which have been grouped with double and string keys:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With