问题描述
Assume that I have a Super Parent - "Super Parent"
Under Super Parent , I have Grand Parent1, Grand Parent2 , Grad Parent3 , This list can be increased by the user
Under Grand Parents , there may be parents , like Parent 1 , Parent 2 , Parent3 etc...this list can also increase
Now Parent1 may have direct kids as File 1, File 2, File 3
But Parent 2 may have more child categories like Sub Parent1, Sub Parent 2 etc ...
So the whole point is , The list can increase horizonatally and vertically without limits at any time
I
am trying to write a LINQ Query that gets alll category names under
Super Parent, Just the Category names not the last File 1 and File 2
etc names, I wrote a query for 2 levels, can some one help me in
getting a generic query out so taht will accomodate any changes to the
tree and my requirement
public Dictionary<int, string> GetMenuCategory()
{
SampleDB db = new SampleDB();
Dictionary<int, string> returnDict = new Dictionary<int, string>();
var query = from q in db.OptionsMenu
where q.ParentMenuID == 3
select q;
foreach (var a in query)
{
returnDict.Add(a.MenuID, a.MenuName);
var query2 = from j in db.OptionsMenu
where j.ParentMenuID == a.MenuID
select j;
foreach (var b in query2)
{
returnDict.Add(b.MenuID, b.MenuName);
}
}
return returnDict;
}
ctrlnick
ctrlnick
推荐答案
{
var x = 来自,q 位于 db.OptionsMenu
var x = from q in db.OptionsMenu
其中 q.ParentID == parentId
where q.ParentID == parentId
选择 新 KeyValuePair < int , 字符串>(q.MenuID,q.MenuName);
select new KeyValuePair<int, string>(q.MenuID, q.MenuName);
返回 x.SelectMany(k => GetMenuCategory(k.Key)).Concat(x);
return x.SelectMany(k => GetMenuCategory(k.Key)).Concat(x);
}
然后您可以通过执行类似"GetMenuCategory(3)"的操作来调用它.
我还建议您使用除Dictionary< int,string>以外的其他容器,因为在Linq上下文中很难使用.
您可以自己获取所有项目的IEnumerable,然后执行所需的任何操作:
}
Then you could call it by doing something like "GetMenuCategory(3)".
I would also advise you to use another container other than Dictionary<int, string>, as it's hard to work with when you're in a Linq context.
You could just fetch an IEnumerable of all the items themselves, then do whatever you want after that:
public 静态 IEnumerable < 商品> GetMenuCategory( int parentId)
public static IEnumerable<Item> GetMenuCategory(int parentId)
{
var x = 来自,q 位于 db.OptionsMenu
var x = from q in db.OptionsMenu
其中 q.ParentID == parentId
where q.ParentID == parentId
选择 q;
select q;
返回 x.SelectMany(k => GetMenuCategory(k.ParentID)).Concat(x);
return x.SelectMany(k => GetMenuCategory(k.ParentID)).Concat(x);
}
这篇关于LINQ查询以获取无尽的子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!