c#阅读' n'来自txt文件的随机行数量

时间:2017-04-11 19:07:43

标签: c# winforms

我试图从包含大约200个条目(行)的文本文件中读取(n)大量随机行,并填充名为" recSongs"的列表框。我提供了一些简单的代码,从文本文件中检索一个随机行,但我想要检索n金额。

这是我的代码。

Sub SplitData()
Dim wsSource As Worksheet, wsState As Worksheet, wsCounty As Worksheet
Dim lr As Long

Application.ScreenUpdating = False

Set wsSource = Sheets("Population Estimates 2010-2015")
lr = wsSource.Cells(Rows.Count, 1).End(xlUp).Row
On Error Resume Next
Set wsState = Sheets("State")
Set wsCounty = Sheets("County")
wsState.Cells.Clear
wsCounty.Cells.Clear
On Error GoTo 0
If wsState Is Nothing Then
    Sheets.Add(after:=wsSource).Name = "State"
    Set wsState = ActiveSheet
End If
If wsCounty Is Nothing Then
    Sheets.Add(after:=wsState).Name = "County"
    Set wsCounty = ActiveSheet
End If

With wsSource.Rows(3)
    .AutoFilter field:=3, Criteria1:="=*county*", Operator:=xlAnd
    wsSource.Range("A3:CW" & lr).SpecialCells(xlCellTypeVisible).Copy wsCounty.Range("A1")
    .AutoFilter field:=3, Criteria1:="<>*county*", Operator:=xlAnd
    wsSource.Range("A3:CW" & lr).SpecialCells(xlCellTypeVisible).Copy wsState.Range("A1")
    .AutoFilter
End With
wsState.UsedRange.Columns.AutoFit
wsCounty.UsedRange.Columns.AutoFit
Application.ScreenUpdating = True
End Sub

8 个答案:

答案 0 :(得分:5)

怎么样:

var lines = File.ReadAllLines("file.txt").OrderBy(x => Guid.NewGuid()).Take(n);

答案 1 :(得分:1)

n将是输入,即你需要的行

List <string> text = File.ReadLines("file.txt").Take(n).ToList();

修改

如果你需要随机线,你可以这样做,

        string[] lines = File.ReadAllLines(@"C:\YourFile.txt");
        List<string> source = new List<string>();
        int n = 10;
        for (int i = 0; i < n; i++)
        {
            source.Add(lines[new Random().Next(lines.Length)]);
        }

答案 2 :(得分:0)

这会将numLines个随机行添加到您的收藏中。请注意,有可能存在重复。

var lines = File.ReadAllLines(@"file.txt");
var r = new Random();
int numLines = 5;

for (int i = 0; i < numLines; i++)
{
    recSongs.Items.Add(lines[r.Next(0, lines.Length - 1)]);
}

要强制执行唯一项目,您可以执行以下操作:

for (int i = 0; i < numLines; i++)
{
    var randomItem = string.Empty;

    do
    {
        randomItem = lines[r.Next(0, lines.Length - 1)];

    } while (recSongs.Contains(randomItem));

    recSongs.Items.Add(randomItem);
}

但现在请注意,它可能永远不会退出。随便的快乐!

答案 3 :(得分:0)

可能最简单的方法,虽然不是最节省内存的方法,但是将文件放入内存中的行集合,然后Shuffle()行,然后采取你想要的许多行:

    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> input)
    {
        var buffer = input.ToArray();
        //Math.Random is OK for "everyday" randomness;
        //use RNGCryptoServiceProvider if you need 
        //cryptographically-strong randomness
        var rand = new Random();

        //As the loop proceeds, the element to output will be randomly chosen
        //from the elements at index i or above, which will then be swapped 
        //with i to get it out of the way; the yield return gives us each 
        //shuffled value as it is chosen, and allows the shuffling to be lazy.
        for (int i = 0; i < buffer.Length; i++)
        {
            int j = rand.Next(i, buffer.Length);
            yield return buffer[j];
            //if we cared about the elements in the buffer this would be a swap,
            //but we don't, so...    
            buffer[j] = buffer[i];
        }
    }

    ...

    string[] fileLines = GetLinesFromFile(fileName); //a StreamReader makes this pretty easy
    var randomLines = fileLines.Shuffle().Take(n);

一些注意事项:

  • 这应该适用于大约200行的文本文件;超过几十万行,你将开始有记忆问题。一个更具可扩展性的解决方案是对一系列行号进行混洗,然后使用它们来寻找和读取你想要的特定行,丢弃所有其他行。
  • 此解决方案以随机顺序生成随机行。如果要保留文件中行的顺序,请执行行号变体,对所选行号进行排序,然后在从文件中读取行后,按行顺序保留行。

答案 4 :(得分:0)

试试这个

var lines = File.ReadAllLines(@"file.txt");
var r = new Random();
int noLines = 10;// n lines

for (int i = 0; i < noLines; i++)
{
    var randomLineNumber = r.Next(0, lines.Length - 1);
    var line = lines[randomLineNumber];
    recSongs.Items.Add(line);
}

答案 5 :(得分:0)

您可以执行以下操作:

HashSet<int> linesHash = new HashSet<int>();
var lines = file.ReadLines();
for (int i = 0; i < numLinesToGet; i++)
{
    int line=0;
    do
    { 
       line = rand.Next(0, lines.Length);
    }while(linesHash.Contains(line));
    linesHash.Add(line);
    linesAdded.Add(lines[line]);
}

请注意,如果要获取的行数大于我的代码永远不会结束的实际行数,那么必须在执行for循环之前完成一些检查。

答案 6 :(得分:0)

var lines = File.ReadAllLines(@"file.txt");
var random = new Random();

var lines = Enumerable.Repeat( -1, n ) // -1 is a filler and is discarded by the select.
.Select( _ => random.Next(0, lines.Length - 1 ) )
.Select( index => lines[index] );

foreach( var line in lines )
{
    recSongs.Items.Add(line);
}

答案 7 :(得分:0)

var lines = File.ReadAllLines(@"file.txt");
var r = new Random();

var randomized = lines.OrderBy(item => r.Next()); //randomize the list
recSongs.Items.AddRange(randomized.Take(N).ToArray()); //Add N amount to listbox

此解决方案还避免重复的randoms