So I have a text file that I need to order its rows by Date and Time as show in the attached screenshot column and I am not sure how
any idea please?
this is what i tried so far
File
.ReadLines(newfile)
.OrderBy(line => DateTime.TryParseExact(
line.Split(" ",StringSplitOptions.RemoveEmptyEntries),
"yyyy MMM d H:m:s.fff", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal, out var dt)
? dt
: DateTime.MaxValue);
>Solution :
You should extract date, parse it and then order by this date.
I can’t see what is the delimeter in your file. If it’s tabulation '\t':
using System.Globalization;
using System.Linq;
...
// Assuming myFile is IEnumerable<string>
var sortedLines = myFile
.OrderBy(line => DateTime.TryParseExact(
line.Split('\t', StringSplitOptions.RemoveEmptyEntries)[1],
"yyyy MMM d H:m:s.fff",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal, out var dt)
? dt
: DateTime.MaxValue); // Incorrect dates will be in the end
If the delimiter is a double space " " then
var sortedLines = myFile
.OrderBy(line => DateTime.TryParseExact(
line.Split(" ", StringSplitOptions.RemoveEmptyEntries)[1],
"yyyy MMM d H:m:s.fff",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal, out var dt)
? dt
: DateTime.MaxValue);
If myFile is a name of the file you should put it as
using System.IO;
...
var sortedLines = File
.ReadLines(myFile)
.OrderBy(...);
Edit: If myFile is FileStream you, technically, can enumerate it like this
static IEnumerable<string> FileLines(FileStream stream) {
using StreamReader reader = new StreamReader(stream, leaveOpen: true);
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
yield return line;
}
and then
var sortedLines = FileLines(myFile)
.OrderBy(...);
but I doubt if you really want Stream here
Edit2: If we don’t know what the delimiter is (in the worst case it is space) we can match date with a help of regular expression:
using System.Text.RegularExpressions;
...
Regex regex = new Regex("[0-9]{4} [A-Z][a-z]+ [0-9]{1,2} [0-9:.]+");
...
.OrderBy(line => DateTime.TryParseExact(
regex.Match(line).Value ?? "",
"yyyy MMM d H:m:s.fff",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal, out var dt)
? dt
: DateTime.MaxValue);