linq 如何从简单文本逐行获取数据

1cklez4t  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(152)

I am trying to extract data from text. It is larger text. For better understanding. I have simple class Test with one atribute result, which is enum.

class Test{

 private Result result;
 
 public Test(string text){
  this.Result = FindProblem(text);
 }
......

public enum Result
    {
        SUCCESS = 1,
        FAIL = 2,
        NONE = 3

    }

 }

Then I have text:
Today at 01:05: (NAME) Failed Backup - The operation encountered an error. (NAME)
Failed when backing up: A file was not found (NAME)
DISK_OPEN_ERROR
Today at 01:04: (NAME) Successful Backup - Backed 42,73 MB (compressed to 7,32 MB).(Duration: 1 minute)
Today at 00:59: (NAME) Successful Backup - Backed 3,41 GB (compressed to 379,17 MB).(Duration: 4 minutes)
And I want each row to return a Test object with results like: result: Failed or result: Succesful.
Method for returning all objects from text

public Result FindResult(string text)
        {
            var splitText = text.Split("\n").ToList();
            Result r = Result.NONE;
            foreach (var item in splitText)
            {
                if (item.Contains("Failed"))
                {
                    r = Result.FAIL;
                }
                else
                {
                    r = Result.SUCCESS;
                }
            }
            return r;
        }

But it returns only result SUCCESS. Expected output

result:FAIL
  result:SUCCESS
  result:SUCCESS
dldeef67

dldeef671#

您可能要做的是在至少2个换行符上拆分,然后使用Select并检查是否包含“Failed”来Map列表中的项目
如果是,则返回Result.FAIL,否则返回Result.SUCCESS,因此函数的返回类型为List<Result>

class Test
{
    private Result result;
    public enum Result
    {
        SUCCESS = 1,
        FAIL = 2,
        NONE = 3    
    }

    public List<Result> FindResult(string text)
    {
         return Regex
        .Split(text, @"\r?\n\s*\r?\n")
        .Select(s => s.Contains("Failed") ? Result.FAIL : Result.SUCCESS)
        .ToList();            
    }
}

然后可以循环返回列表中的项

Test test = new Test();
var results = test.FindResult(input);
foreach(var r in results) {
    Console.WriteLine(r);
}

输出量

FAIL
SUCCESS
SUCCESS

请参见C# demo

相关问题