I want to get random number of lines(let's say 2 ) group by Code from text file.
for e.g.
4581511: 50.27: AT
1223522: 86.99: AT
7456117: 68.59: QW
5261789: 39.17: QW
.....
.....
Text File
bookNumber Price Code
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
I got this far and I am geting 2 lines which are not random but in sequence
Code
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;
}
}
}
Any Ideas?
Thanks