这是我的课程结构和示例数据,
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; }
}
================================================ ==============================================
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"}
}
}
}
};
现在基于DataType
,我想像下面的集合那样隔离。示例是Double,类似于string。在collectionResult
中,我需要添加Asset
和来自各种实例的所有double数据类型集合属性。这可能吗?
var collectionResult = new CollectionResult
{
Asset = "A1",
DoubleInstances = new List<Instance>
{
new Instance
{
Name = "Instance-1",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "N1", Value = 10, DataType = "Double"}
}
},
new Instance
{
Name = "Instance-2",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "N1", Value = 20, DataType = "Double"}
}
}
}
};
您可以创建一个新实例,并仅使用Where()
过滤Doubles:
var doubleCollection = new CollectionResult
{
Asset = collectionResult.Asset,
Instances = collectionResult.Instances.Select(x => new Instance {
Name = x.Name,
CollectionProperties = x.CollectionProperties.Where(cp => cp.DataType == "Double").ToList()
}).ToList()
};
您还可以创建一种方法,以按传入的属性进行过滤:
private static CollectionResult FilterCollectionByProperty(CollectionResult collectionResult, Func<CollectionProperty, bool> selector)
{
return new CollectionResult
{
Asset = collectionResult.Asset,
Instances = collectionResult.Instances.Select(x => new Instance
{
Name = x.Name,
CollectionProperties = x.CollectionProperties.Where(selector).ToList()
}).ToList()
};
}
并创建Double和String集合,如下所示:
var doubleCollection = FilterCollectionByProperty(collectionResult, x => x.DataType == "Double");
var stringCollection = FilterCollectionByProperty(collectionResult, x => x.DataType == "String");
您可以使用Double
方法删除所有类型与RemoveAll
不同的集合属性
RemoveAll