LINQ TO XML(通过申请一组组Linq命令)

时间:2014-03-27 05:58:59

标签: c# xml linq sorting

我有以下格式的数据

ParentID                            GoalID   GoalName
PId:0#Position:1#Level:1            31       Default Folder
PId:0#Position:2#Level:1            32       Folder 1
PId:0#Position:3#Level:1            33       Folder 2
PId:31#Position:1#Level:2           34       Sub-Folder in Default Folder

此处L1P1表示第1级和第1位。

我想要的是我想根据等级和位置对此进行排序,以便数据看起来像

ParentID                            GoalID   GoalName
PId:0#Position:1#Level:1            31       Default Folder
PId:31#Position:1#Level:2           34       Sub-Folder in Default Folder
PId:0#Position:2#Level:1            32       Folder 1
PId:0#Position:3#Level:1            33       Folder 2

我在XElement中有以上数据,并应用排序但无法获得所需的输出。

参考:我也看了this但没有成功

我如何实现这一目标。

2 个答案:

答案 0 :(得分:1)

这对我有用:

var lookup = items.ToLookup(x => x.ParentID);

Func<int, IEnumerable<Goal>> treeOrder = null;
treeOrder = n =>
    lookup[n].SelectMany(x => new [] { x, }.Concat(treeOrder(x.GoalID)));

var results = treeOrder(0);

我得到以下输出:

Results


集合items是:

var items = new []
{
    new Goal { TreeID = "L1P1", ParentID = 0, GoalID = 31, GoalName = "Default Folder" },
    new Goal { TreeID = "L1P2", ParentID = 0, GoalID = 32, GoalName = "Folder 1" },
    new Goal { TreeID = "L1P3", ParentID = 0, GoalID = 33, GoalName = "Folder 2" },
    new Goal { TreeID = "L2P1", ParentID = 31, GoalID = 34, GoalName = "Sub-Folder in Default Folder" },
};

用这个类定义:

public class Goal
{
    public string TreeID;
    public int ParentID;
    public int GoalID;
    public string GoalName;
}

答案 1 :(得分:1)

假设您的数据类似于以下格式:

<Tree>
    <TreeID>L1P1</TreeID>
    <ParentID>0</ParentID>
    <GoalID>31</GoalID>
    <GoalName>Default Folder</GoalName>
</Tree>

基本上你想先按位置排序,然后按级别排序:

var trees = doc.Descendants("Tree")
    .OrderBy(x => Convert.ToInt32(x.Element("TreeID").Value.Substring(x.Element("TreeID").Value.IndexOf("P") + 1)))
    .ThenBy(x => Convert.ToInt32(x.Element("TreeID").Value.Substring(1, x.Element("TreeID").Value.IndexOf("P") - 1)))
    .ToList();