我希望输出像
Test Genre1/
Test Genre2/
Test Genre3/Test genre1 //(Bcoz id 1 as Test Genre1)
Test Genre4/Test genre2 //(Bcoz id 2 as Test Genre2)
Test genre1/Test Test genre3/Genre5 //(Bcoz id 3 as Test Genre3)
它应该是id
中parent id
和Linq
的组合。
任何帮助将不胜感激......
答案 0 :(得分:1)
您可以尝试返回在实体类上定义的IEnumerable
的递归方法:
public class Genre
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public IEnumerable<Genre> GetSelfAndAncestors(IEnumerable<Genre> items)
{
yield return this;
if (ParentId.HasValue)
{
var parent = items.First(x => x.Id == ParentId.Value);
foreach (var ancestor in parent.GetSelfAndAncestors(items))
{
yield return ancestor;
}
}
}
}
用法:
var genres = new[]
{
new Genre {Id = 1, Name = "Test Genre 1", ParentId = null},
new Genre {Id = 2, Name = "Test Genre 2", ParentId = null},
new Genre {Id = 3, Name = "Test Genre 3", ParentId = 1},
new Genre {Id = 4, Name = "Test Genre 4", ParentId = 2},
new Genre {Id = 5, Name = "Test Genre 5", ParentId = 3}
};
foreach (var genre in genres)
{
var path = genre.GetSelfAndAncestors(genres);
Console.WriteLine(String.Join("/", path.Select(x => x.Name)));
}
如果树很深,您可能会发现将此实现与非IEnumerable
实施相比有显着的性能影响。
答案 1 :(得分:1)
给定一个递归调用的方法
private static string SelectGenreName(IEnumerable<Genre> all, Genre g)
{
var s = g.Name + '/';
if(g.ParentId.HasValue){
s += SelectGenreName(all, all.Single(x => x.Id == g.ParentId.Value));
}
return s;
}
获得合理结果的代码*非常简单:
*明智的结果;您的上一个示例与之前的示例相反。上面的示例按照前四个示例给出了结果。即Child/Parent/Grandparent
var genres = new[]
{
new Genre {Id = 1, Name = "Test Genre 1", ParentId = null},
new Genre {Id = 2, Name = "Test Genre 2", ParentId = null},
new Genre {Id = 3, Name = "Test Genre 3", ParentId = 1},
new Genre {Id = 4, Name = "Test Genre 4", ParentId = 2},
new Genre {Id = 5, Name = "Test Genre 5", ParentId = 3}
};
var result = genres.Select(g => SelectGenreName(genres,g));
foreach(var r in result)
Console.WriteLine(r);
答案 2 :(得分:0)
创建一个递归函数并在你的linq中使用该函数。像这样的东西。
//Recursive method
private static string GetParentPath( IEnumerable<Item> items , Item item )
{
if (item.ParentId.HasValue)
{
return GetParentPath(items, items.First(i => i.Id == item.ParentId)) + "/" + item.GenreName;
}
return item.GenreName;
}
var items = new Item[]
{
new Item {Id = 1, GenreName = "Test Genre 1", ParentId = null},
new Item {Id = 2, GenreName = "Test Genre 2", ParentId = null},
new Item {Id = 3, GenreName = "Test Genre 3", ParentId = 1},
new Item {Id = 4, GenreName = "Test Genre 4", ParentId = 2},
new Item {Id = 5, GenreName = "Test Genre 5", ParentId = 3}
};
// Linq query
var result = from child in items
select new { Path = GetParentPath(items, child) };
//Class used in example
public class Item
{
public int Id { get; set; }
public string GenreName { get; set; }
public int? ParentId { get; set; }
}