Created
July 18, 2012 07:00
-
-
Save jinweijie/3134705 to your computer and use it in GitHub Desktop.
Linq2XMLGroupBy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Xml.Linq; | |
/// <summary> | |
/// Linq2XMLGroupBy | |
/// </summary> | |
public class Linq2XMLGroupBy | |
{ | |
public static string ConcatValue(IGrouping<string, XElement> g) | |
{ | |
string result = string.Empty; | |
foreach(var v in g.Elements("Value")) | |
{ | |
result += (v.Value + ","); | |
} | |
if(result.EndsWith(",")) | |
result = result.Substring(0, result.Length - 1); | |
return result; | |
} | |
/// <summary> | |
/// The main entry point for the application | |
/// </summary> | |
[STAThread] | |
public static void Main( string[] args ) | |
{ | |
string content = @" | |
<ParameterValues> | |
<ParameterValue> | |
<Name>Instance</Name> | |
<Value>199</Value> | |
</ParameterValue> | |
<ParameterValue> | |
<Name>Branch</Name> | |
<Value>62</Value> | |
</ParameterValue> | |
<ParameterValue> | |
<Name>Branch</Name> | |
<Value>63</Value> | |
</ParameterValue> | |
</ParameterValues> | |
"; | |
XElement root = XElement.Parse(content); | |
var q = from item in root.Descendants("ParameterValue") | |
group item by item.Element("Name").Value into itemGroup | |
select new { itemGroup.Key, V = ConcatValue(itemGroup)}; | |
foreach(var item in q.ToList()) | |
{ | |
Console.WriteLine( string.Format("key:{0}, value:{1}", item.Key, item.V)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment