我认为没有真正简单的方法可以做到这一点。不过,我已经确定了这一点,这可能会让你开始:
var myData = new []
{
new { Name = "Bill", Action="aaa", Id = "832758" },
new { Name = "Tony", Action="aaa", Id = "82fd58" },
new { Name = "Bill", Action="bbb", Id = "532758" },
new { Name = "Tony", Action="bbb", Id = "42fd58" }
};
// group all the Names together
var result = from m in myData
group m by m.Name into names
orderby names.Key
select names;
// go through each Name group and create the output string to store in sbLines
var sbLines = new StringBuilder();
foreach (var name in result)
{
var sb = new StringBuilder();
sb.AppendFormat("Name: {0}, ", name.Key);
int count = 1;
foreach (var item in name)
{
if(count > 1)
sb.AppendFormat("Action_{0}: {1}, ", count, item.Action);
else
sb.AppendFormat("Action: {0}, ", item.Action);
count++;
}
count = 1;
foreach (var item in name)
{
if(count > 1)
sb.AppendFormat("Id_{0}: {1}, ", count, item.Id);
else
sb.AppendFormat("Id: {0}, ", item.Id);
count++;
}
sbLines.Append(sb.ToString().Trim(new char[] { ' ',',' }));
sbLines.Append(Environment.NewLine);
}
Console.WriteLine(sbLines.ToString());
在这里运行它:http: //ideone.com/8UTxr