从group text获取文本文件中的随机行数

时间:2010-01-05 04:33:59

标签: c# linq

我希望从文本文件中按代码获得随机数行(比方说2)。

例如。

4581511:50.27:AT
1223522:86.99:AT 7456117:68.59:QW
5261789:39.17:QW
.....
.....

文本文件

bookNumber价格代码
4581511:50.27:AT
7841522:26.13:AT
7353532:96.13:AT
1223522:86.99:AT 8415621:89.70:IT
8411442:82.42:IT
4555577:19.14:IT
7655577:65.45:IT
2754831:35.44:DR
1364449:82.47:DR
4545454:45.65:DR
8795457:78.36:DR
5261789:39.17:QW
7845522:10.42:QW
7456117:68.59:QW
4346129:23.78:QW

我到目前为止,我正在制作2行,这些行不是随机的,而是顺序的

代码

static IEnumerable<string> ReadLines(string path)
    {

        using (var file = File.OpenText(path))
        {
            string line;
            while ((line = file.ReadLine()) != null)
            {
                if (line.Contains(":"))
                {
                    yield return line;
                }
            }
        }
    } 

    public static IEnumerable<string> GetrandomLines()
    {

        string filepath = "file location";
        var readTextFile = ReadLines(filepath);
        var codeGroup = readTextFile.GroupBy(line => line.Substring(line.Length - 2))
                          .Select(g => new
                          {
                            value = g.Key,
                            count = g.Count()
                           });


        foreach (var item in codeGroup)
        {
            Random randomLineGenerator = new Random(DateTime.Now.Millisecond);
             var randomLines = (from x in readTextFile
                                where x.Substring(x.Length - 2) == item.value
                                select x).Skip(randomLineGenerator.Next(0, item.count)).Take(2);
             foreach (var line in randomLines)
             {
                 yield return line;
             }
        }

    }

任何想法?

由于

2 个答案:

答案 0 :(得分:1)

Guid版本,随机值不能相同。

public static IEnumerable<string> GetrandomLines2(string filePath, int lines)
{
    return ReadLines(filePath)
        .GroupBy(line => line.Substring(line.Length - 2))
        .SelectMany(s => s.OrderBy(g => Guid.NewGuid()).Take(lines));
}

随机版本,两个随机值可能相同。

public static IEnumerable<string> GetTwoRandomLines(string filePath)
{
    var codeGroup = ReadLines(filePath)
        .GroupBy(line => line.Substring(line.Length - 2));

    Random rnd = new Random(DateTime.Now.Millisecond);

    foreach (var item in codeGroup)
    {
        yield return item.Skip(rnd.Next(item.Count())).FirstOrDefault();
        yield return item.Skip(rnd.Next(item.Count())).FirstOrDefault();
    }
}

答案 1 :(得分:0)

这样的事情怎么样?

    public IEnumerable<string> GetRandomLines(string path, int lines)
    {
        foreach (var line in File.ReadAllLines(path).OrderBy(s => Guid.NewGuid()).Take(lines))
        {
            yield return line;
        }
    }