我试图从包含大约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
答案 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);
一些注意事项:
答案 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