简体   繁体   中英

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.

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

  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:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM