CollectionProperties上的筛选器为我提供了全部4条记录,而不是2条



我有一个列表lstCollectionInstances,它有4个集合实例,

var lstCollectionInstances = new List<CollectionInstance>
{
new CollectionInstance
{
Name = "A",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P1", Value = 10, DataType = "D"}
}
},
new CollectionInstance
{
Name = "A",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P2", Value = "H1", DataType = "S"}
}
},
new CollectionInstance
{
Name = "B",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P1", Value = 20, DataType = "D"}
}
},
new CollectionInstance
{
Name = "B",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P2", Value = "H2", DataType = "S"}
}
},
};

现在,当我根据CollectionProperty数据类型D对其进行筛选时,它应该给我2条记录,但下面的代码给了我所有4条记录,这里缺少什么?

var X = lstCollectionInstances.Select(x => new CollectionInstance
{
Name = x.Name,
CollectionProperties = x.CollectionProperties.Where(cp => cp.DataType == "D").ToList()
}).ToList();

此选项选择属性为D类型的所有实例。

var result= lstCollectionInstances
.Where(x => x.CollectionProperties.Any(y => y.DataType == "D"))
.ToList();

这是因为在lstCollectionInstances的每个项中执行Select,在CollectionProperties中执行Where。它将返回4个项目,其中2个项目的CollectionProperties为空。您应该首先执行Where,如:

var X = lstCollectionInstances.Where(a => a.CollectionProperties.Any(cp => cp.DataType == "D")).Select(x => new CollectionInstance
{
Name = x.Name,
CollectionProperties = x.CollectionProperties
}).ToList();

最新更新