グループ化のサンプルを次に示します。
XDocument doc = XDocument.Load("../../XMLFile1.xml");
var groups = from msg in doc.Root.Elements("Msg")
where !((string)msg.Attribute("UserText")).StartsWith("start")
group msg by
msg.ElementsBeforeSelf("Msg").Where(m =>
((string)m.Attribute("UserText")).StartsWith("start")).Last();
foreach (var group in groups)
{
Console.WriteLine("Group starting with {0} has {1} member(s).",
group.Key.Attribute("UserText"), group.Count());
}
XML 入力サンプル XMLFile1.xml は、
<Root>
<Msg UserText="start 0">
</Msg>
<Msg UserText="A">
</Msg>
<Msg UserText="A">
</Msg>
<Msg UserText="start 1">
</Msg>
<Msg UserText="A">
</Msg>
<Msg UserText="start 2">
</Msg>
<Msg UserText="A">
</Msg>
<Msg UserText="A">
</Msg>
<Msg UserText="A">
</Msg>
</Root>
出力を取得します
Group starting with UserText="start 0" has 2 member(s).
Group starting with UserText="start 1" has 1 member(s).
Group starting with UserText="start 2" has 3 member(s).