[英]Find top-level parent in List with LINQ
I have a List of user-defined objects that have an ID and a ParentID. 我有一个具有ID和ParentID的用户定义对象列表。 The list looks something like this.
列表看起来像这样。
ParentID ID
123 345
123 456
456 567
456 678
678 789
I need a LINQ statement to find the top level parent; 我需要一个LINQ语句来查找顶级父级; that is, all of the objects where the ParentID does not exist in as an ID (in this example, only 123).
也就是说,ParentID不存在的所有对象都作为ID(在本例中,仅为123)。
Here is what I have so far and it is returning 567,678,789. 这是我到目前为止,它返回567,678,789。
parentList = baseList.Where(b => !baseList.Select(o => o.ParentID).Distinct().Contains(b.ID)).ToList();
Your current query is trying to find all the items where their ID doesn't correspond to any other item's parent ID--in other words, you're finding all childless nodes. 您当前的查询正在尝试查找其ID与任何其他项目的父ID不对应的所有项目 - 换句话说,您正在查找所有无子节点。
What it sounds like you want is all the parentless nodes--those whose parent ID doesn't match any other item's ID. 你想要的是所有无父节点 - 那些父ID与任何其他项的ID不匹配的节点。
var ids = new HashSet<int>(baseList.Select(o => o.ID));
var itemsWithNoParent = baseList.Where(o => !ids.Contains(o.ParentID))
.ToList();
I'm using a HashSet<>
to ensure reasonable .Contains()
performance on large collections. 我正在使用
HashSet<>
来确保对大型集合的合理.Contains()
性能。
Also: 也:
parentList = baseList
.where(parent => !baseList.Any(possibleParent => possibleParent.ID == parent.ParentID))
.ToList();
I use this a lot on small (less than 100,000) collections. 我在小型(少于100,000)集合中使用了很多。
I might as well add this too; 我也可以加上这个; how to easily create a tree view from this:
如何从这里轻松创建树视图:
public class Node
{
public int Id { get; set; }
public int ParentId { get; set; }
public IEnumerable<Node> Nodes { get; set; }
public Node ParentNode { get; set; }
}
IEnumerable<Node> nodes = .....
nodeTree = nodes.Select(n =>
{
n.Nodes = nodes.Where(n2 => n2.ParentId == n.Id).ToList();
n.ParentNode = nodes.FirstOrDefault(n2 => n2.Id == n.ParentId)
return n;
})
.Where(n => n.ParentNode == null)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.