[英]LINQ query to generate XML type output on console windows and XML file
I am new to programming and still learning, working on LINQ I created a very small code that grouped an array of int in the form of batches, the LINQ query that I am using display a simple output, which is not my requirement, I want the following output on CONSOLE WINDOWS using LINQ query please help me.我是编程新手,仍在学习,使用 LINQ 我创建了一个非常小的代码,以批处理的形式对 int 数组进行分组,我使用的 LINQ 查询显示一个简单的输出,这不是我的要求,我想要使用 LINQ 查询的 CONSOLE WINDOWS 上的以下输出请帮助我。
Output on Console Window控制台窗口上的输出
<Results>
<Result>
<Marks>60</Marks>
<Marks>50</Marks>
<Marks>70</Marks>
<Total>180</Total>
</Result>
<Result>
<Marks>30</Marks>
<Marks>80</Marks>
<Marks>65</Marks>
<Total>175</Total>
</Result>
<Result>
<Marks>90</Marks>
<Marks>75</Marks>
<Marks>55</Marks>
<Total>220</Total>
</Result>
My Code is我的代码是
static void Main(string[] args)
{
List<int> email = new List<int>() { 60, 50, 70, 30, 80, 65, 90, 75, 55 };
foreach (var batch in email.Batch(3))
{
Console.WriteLine(String.Join(",", batch));
}
Console.ReadLine();
}
LINQ Query LINQ 查询
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items,
int maxItems)
{
return items.Select((item, inx) => new { item, inx })
.GroupBy(x => x.inx / maxItems)
.Select(g => g.Select(x => x.item));
}
Yes, LINQ to XML makes this very simple - you can pass elements, including sequences of elements, into the XElement
constructor, and they're included in a nested way:是的,LINQ to XML 使这变得非常简单 - 您可以将元素(包括元素序列)传递到XElement
构造函数中,并且它们以嵌套方式包含在内:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Xml.Linq;
static class Extensions
{
public static IEnumerable<IEnumerable<T>> Batch<T>(
this IEnumerable<T> items, int maxItems) =>
items.Select((item, inx) => new { item, inx })
.GroupBy(x => x.inx / maxItems)
.Select(g => g.Select(x => x.item));
}
class Program
{
static void Main(string[] args)
{
List<int> email = new List<int>() { 60, 50, 70, 30, 80, 65, 90, 75, 55 };
var element = new XElement("Results",
email.Batch(3)
// Each batch creates a new Result element
.Select(batch =>
new XElement("Result",
// Each element of the batch creates a Mark
batch.Select(mark => new XElement("Mark", mark)),
// The batch also has a Total element
new XElement("Total", batch.Sum()))));
Console.WriteLine(element);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.