我有以下类结构,
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; }
}
我有以下集合结果,其中 2 个实例具有各种集合属性,具有 2 种数据类型 double 和字符串。
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"}
}
}
}
};
现在我的目标是将收集结果拆分为不同的实例,并根据数据类型对它们进行分组。使用下面的代码,我可以拆分 put,但它给了我 4 个集合结果,但它应该给出 2 个(2 个用于 double ,2 个用于字符串),请建议。谢谢!
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
});
最佳答案
您只需在 selectMany
之后添加一个 GroupBy
语句即可:
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);
这样您将拥有两个组,它们已使用双键和字符串键分组:
关于c# - 如何根据DataType组合 "collectionResult",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60738027/