The following dataset is available:
var Data = new[] { new Data{Id = 1, ParentId = 0, Value = "value1"}, new Data{Id = 2, ParentId = 1, Value = "value1"}, new Data{Id = 3, ParentId = 1, Value = "value3"}, new Data{Id = 4, ParentId = 3, Value = "value4"} }; and the method that needs to be implemented in such a way that, given Id, I could get a list of all its ParentId and preferably Value
Spit time:
Dictionary<int, string> dict = new Dictionary<int, string>(); public void AllParents(IEnumerable<Data> Data, int id) { var parent = Data.First(x=>x.Id==id); dict.Add(parent.Id, parent.Value); if(parent.ParentId == 0) return; AllParents(Data, parent.ParentId); } AllParents(Data, 4); AllParents(Data, 2); +---------+---------+ +----------+---------+ |Key |Value | | Key | Value | |---------|---------| |----------|---------| |4 |value4 | | 2 | value2 | |3 |value3 | | 1 | value1 | |1 |value1 | | | | | | | | | | | | | | | | +---------+---------+ +----------+---------+ But how to do the same if the data is in a table in the database? Splitting one table into two or changing the data structure in any other way is the only way out?