如何将包含 "Error" 的列表条目放入另一个列表?

How to put list entries that contain "Error" in another list?

我正在用 Visual C# 编写一个程序来过滤 .log 文件中的错误消息并显示它们。有一个名为 "contentList" 的列表,还有一个名为 "errorList"

的列表
void BtnCheckLeft_Click(object sender, EventArgs e)
{
    SearchForErrors(_ContentListLeft);
}

void BtnCheckRight_Click(object sender, EventArgs e)
{
    SearchForErrors(_ContentListRight);
}

void SearchForErrors(List<string> contentList)
{
    int searchIndex = 1;
    List<string> errorList = new List<string>();
    while(searchIndex != errorList.Count)
    {
        var bla = contentList.BinarySearch("Error");
        searchIndex += 1;
    }

    MessageBox.Show("Following errors were spotted:\n\n" + errorList.ToString() + "\n \n \n", "placeholder", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
}

contentList 包含所选 .log 文件的每一行,现在我想将所有包含单词 error 的条目放入列表 "errorList" 并显示它。我的问题是 BinarySearch 什么也没找到,bla(我的占位符 var)始终为 -1,我不知道另一种管理方法。 也许您知道为什么 BinarySearch 什么也找不到,或者您知道另一种显示错误行的方法。

如果您的日志文件是文本文件,那么您可以这样做:

string result = string.Empty;
var lines = File.ReadAllLines("myLogFile.txt");
foreach (var line in lines)
{
    if(line.Contains("Error"))
    {
        errorList.Add(line);
    }
}

BinarySearch 将搜索 整个元素 ,而不是它的一部分。因此,如果您有像 "This is an Error" 这样的行,BinarySearch 将 return -1,因为该行不 等于 字符串 "Error",但 包含 它。

您想要的是检查是否有任何元素 包含 单词 "Error":

var errorLines = contentList.Where(x => x.Contains("Error"));

我可能不熟悉 BinaryList 但这里有一些来自 foreach 循环的帮助..

//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            List<string> errorList = new List<string>();
            List<string> newList = new List<string>();
            errorList.Add("one error");
            errorList.Add("some text");
            errorList.Add("two error");
            errorList.Add("some text");
            errorList.Add("some text");
            errorList.Add("some text");
            errorList.Add("three error");
            errorList.Add("four error");
            errorList.Add("some text");
            errorList.Add("some text");
            foreach(string item in errorList){
                if(item.Contains("error")){
                    newList.Add(item);
                }
            }

            foreach(string item in newList){
                Console.WriteLine(item);
            }
        }
    }
}

希望对您有所帮助!