How can I do this in one linq statement: If got an list of objects where I have (id, name, parentId). Now I have 3 levels of hierarchy in this list. What I want is that when I'm getting the Id of the top level in my function, I want the Ids of the 3th level.
I've got this for the moment:
Public List<int> GetIds(int objectId){
var idList = new List<int>();
//get the seconds level ids
var parentsIds = from n in myListObject
开发者_如何学JAVA where n.parentId.equals(objectId)
select n.id;
//get the third level ids
foreach(var parentId in parentsIds){
var childIds = from c in myListObject
where c.parentId.equals(parentId)
select c.id;
foreach(var childId in childIds){
idList.Add(childId);
}
}
return idList;
}
So I'm wondering if I could do this in one linq statement?
I have not tested it, but something similar to this should work:
myListObject
.Where(child =>
myListObject
.Where(obj => obj.parentId==objectId)
.Select(obj => obj.id)
.Contains(child.parentId))
.Select(child => child.Id);
精彩评论