gpt4 book ai didi

linq - 使用 Linq 解析文本文件

转载 作者:行者123 更新时间:2023-12-04 22:58:20 24 4
gpt4 key购买 nike

我有一个格式如下的日志文件,您可以看到每个日志都以时间开头,以竖线分隔符结尾。

将每个以日期时间开始并以竖线分隔符结束的日志放入列表中

如何解析此文本文件并将日志放入集合中?我似乎在确定如何找到日志的开头和结尾并在每个日志中读取它时遇到问题

下面是一个简单的示例,可以让您了解我正在尝试做什么。任何指针帮助等......非常感谢

日志示例

        08:52:03.260|Error| Stack Trace and other info removed here|
lots of info about the stack trace
lots of info about the stack trace
lots of info about the stack trace
lots of info about the stack trace
lots of info about the stack trace|
09:52:03.260|Error| Stack Trace and other info removed here|
lots of info about the stack trace
lots of info about the stack trace
lots of info about the stack trace
lots of info about the stack trace
lots of info about the stack trace|
09:52:03.260|Error|Stack Trace and other info removed here|
lots of info about the stack trace
lots of info about the stack trace
lots of info about the stack trace
lots of info about the stack trace
lots of info about the stack trace|

文件 2 场景 我的订单

        Quantity Description                    Price
1 shoes £1.00
Total £1.00
No: 34343345


=============================================
My Order


Quantity Description Price
1 TShirt £1.00
Total £1.00
No: 32234234



============================================

程序:

  class Program
{
static void Main(string[] args)
{
string path = @"MyTestLog.log";
string aa = string.Empty;

List<LogMessage>logMessages=new List<LogMessage>();
using (StreamReader reader = new StreamReader(path))
{
//????
logMessages.Add(new LogMessage
{
Time = ??,
ErrorLevel = ,
Details = ??
});
}
}
}

public class LogMessage
{
public DateTime Time { get; set; }
public string ErrorLevel { get; set; }
public string Details { get; set; }
//other stuff here
}

最佳答案

你可能想试试这个:

var list =
from line in File.ReadAllLines("log.txt")
where line.EndsWith("|")
let parts = line.Split('|')
where parts.Length >= 2
where IsDateTime(parts[0])
select new LogMessage()
{
Time = DateTime.Parse(parts[0]),
ErrorLevel = parts[1],
Details = parts[2]
};

还有这个简单的辅助方法:

private static bool IsDateTime(string time)
{
DateTime temp;
return DateTime.TryParse(time, out temp);
}

更新:当你使用 .NET 4.0 时,你应该使用 File.ReadLines而不是 File.ReadAllLines。这可以防止将整个文件加载到内存中。

关于linq - 使用 Linq 解析文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3741149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com