Reputation: 899
I have a plain list of persons List<Person>
public class Person
{
public int Id { get; set; }
public int ParentId { get; set; }
public List<Person> Childs { get; set; }
}
so I want to sort it to have a list of persons without a ParentId
and all children of a person are added to his Childs
. I've no idea how to do it, any tips?
Upvotes: 0
Views: 182
Reputation: 117029
This should work a treat:
var lookup = people.ToLookup(p => p.ParentId);
foreach (var person in people)
{
person.Childs = lookup[person.Id].ToList();
}
If the Childs
collection is already instantiated then use this:
person.Childs.AddRange(lookup[person.Id]);
Upvotes: 1
Reputation: 125620
I'm not sure what you're asking for, but seems like you're trying to get tree-like structure form single-dimmentional list of Person
.
var dict = source.ToDictionary(x => x.Id);
foreach(var p in source)
if(p.ParentId != 0)
dict[p.ParentId].Childs.Add(p);
var topLevel = source.Where(p => p.ParentId == 0).ToList();
I assumed ParentId == 0
means there is no parent, and that item is top level item.
Upvotes: 1