-1

I have an array of string that contains 1000 lines, how to take each 25 lines and group them into one text using linq c#. I can use loops , but I need the code using linq.

4

3 回答 3

3
var blocks = File.ReadLines(filename)
                    .Select((s, i) => new { s, i })
                    .GroupBy(x => x.i / 25)
                    .Select(g => String.Join(" ", g.Select(x => x.s)))
                    .ToList();

您还可以使用 Morelinq 的 Batch 方法:https ://code.google.com/p/morelinq/source/browse/MoreLinq/Batch.cs

于 2015-07-26T15:53:36.227 回答
2

当问题是关于一个简单的 linq 时,我认为,答案应该既好看又高效。所以,我准备了一个测试用例。

由于这是一个社区维基,请随时更新它..

var arr = Enumerable.Range(0, 20000).Select(x => x.ToString()).ToArray();

var t1 = Measure(() =>
{
    var blocks = arr
                .Select((s, i) => new { s, i })
                .GroupBy(x => x.i / 25)
                .Select(g => String.Join(" ", g.Select(x => x.s)))
                .ToList();
}, 1000);


var t2 = Measure(() =>
{
    var allLines = new List<string>();
    for (int i = 0; i < arr.Length; i += 25)
    {
        allLines.Add(String.Join(" ", arr.Skip(i).Take(25)));
    }

}, 1000);


var t3 = Measure(() =>
{
    int count = 0;
    var blocks = arr
                .GroupBy(x => count++ / 25)
                .Select(g => String.Join(" ", g))
                .ToList();
}, 1000);


var t4 = Measure(() =>
{
    var blocks = arr.Batch(25, x => x)
                .Select(g => String.Join(" ", g))
                .ToList();
}, 1000);


Console.WriteLine("EZI: {0}\nShar1er80: {1}\nModified-EZI: {2}\nMoreLinq'sBatch: {3}", t1,t2,t3,t4);

long Measure(Action action, int n)
{
    action();
    var sw = Stopwatch.StartNew();
    for (int i = 0; i < n; i++)
    {
        action();
    }
    return sw.ElapsedMilliseconds;
}

输出:

EZI: 3548
Shar1er80: 24362
Modified-EZI: 1782
MoreLinq'sBatch: 1300
于 2015-07-26T18:32:51.563 回答
1

因为您已经take在问题中添加了标签,所以您可以使用以下方法获得与 @EZI 相同的结果Take()from Linq

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> _1000Lines = new List<string>();
        for (int i = 1; i <= 1000; i++)
            _1000Lines.Add(i.ToString());

        for (int i = 0; i < _1000Lines.Count; i += 25) 
        {
            // Use Skip() to skip the previous 25 items from the previous iteration
            Console.WriteLine(String.Join(" ", _1000Lines.Skip(i).Take(25)));
        }
    }
}

小提琴演示

于 2015-07-26T17:46:15.543 回答