【发布时间】:2016-07-03 15:04:55
【问题描述】:
我有一些物品。一个项目可以有另一个项目,另一个项目可以有另一个项目。以此类推。
我不知道嵌套项可以有多少级项。嵌套项的级别可以在运行时定义。
class Person
{
Person person;
public Person(Person _nestedPerson)
{
person = _nestedPerson;
}
public bool IsSelectedPerson { get; set; }
public string Name { get; set; }
}
以及如何嵌套项目(Person):
IList<Person> list = new List<Person>();
for (int startIndex = 0; startIndex < 5; startIndex++)
{
list.Add(new Person(new Person(new Person(new Person(null) { Name="Bill",
IsSelectedPerson=true})) { Name = "Jessy", IsSelectedPerson = false })
{ Name = "Bond", IsSelectedPerson =true});//3 nested persons
list.Add(new Person(new Person(null) { Name = "Kendell",
IsSelectedPerson = true }) { Name="Rosy", IsSelectedPerson=true});//2 nested persons
//The next time it can be just one person without nested item(person). I do not know how many items(persons) will be nested
//list.Add(new Person(null) { Name="Rosy", IsSelectedPerson=true});
}
我的目标是获取IsSelectedPerson=true 的人(Person) 的所有 个对象(没有重复)?
我玩过Select()
var ee = list.Select(x=>x.IsSelectedFacet==true);//comparison should be done here
但这不是我想要的,它只需要bool 值。
更新:
我的预期结果应该是拥有一个具有唯一名称的 Person 对象。不管有多少同名的对象。我只想拿一个对象。抱歉误导。它应该是这样的:
【问题讨论】:
-
您对嵌套深度有任何限制吗?
-
FacetStorage.Where(p => p.IsSelectedFacet); -
@Valentin 不,嵌套深度没有限制
-
@Jodrell 是的,我试过
coll.Where(p => p.IsSelectedPerson);,但这个查询只接受上层对象,而不是嵌套对象。 -
@StepUp,首先你需要“扁平化”嵌套的人。有几种方法可以做到这一点,我更喜欢一种不涉及分配任意长列表的 linq 方式。