Получение 2 строк над текущей строкой в ​​текстовом файле C# - PullRequest
0 голосов
/ 12 июля 2020

У меня есть foreach l oop, и для каждой строки мне нужно получить 2 предыдущие строки и сохранить их в переменной. Как бы я это сделал? Я так долго пытался это выяснить.

Размер файла около 5 МБ

Мой foreach l oop:

        foreach (string line in File.ReadAllLines("DeadByDaylightCopy.log"))
        {
            if (line.Contains("LogCustomization: --> TW"))
            {
                killer = "Wraith";
            }

            else if (line.Contains("LogCustomization: --> TR"))
            {
                killer = "Trapper";
            }

            else if (line.Contains("LogCustomization: --> HK"))
            {
                killer = "Spirit";
            }

            else if (line.Contains("LogCustomization: --> MK"))
            {
                killer = "Plague";
            }

            else if (line.Contains("LogCustomization: --> FK"))
            {
                killer = "Pig";
            }

            else if (line.Contains("LogCustomization: --> OK"))
            {
                killer = "GhostFace";
            }

            else if (line.Contains("LogCustomization: --> TN"))
            {
                killer = "Nurse";
            }

            else if (line.Contains("LogCustomization: --> KK"))
            {
                killer = "Legion";
            }

            else if (line.Contains("LogCustomization: --> BE"))
            {
                killer = "Huntress";
            }

            else if (line.Contains("LogCustomization: --> TC"))
            {
                killer = "Billy";
            }

            else if (line.Contains("LogCustomization: --> WI"))
            {
                killer = "Hag";
            }

            else if (line.Contains("LogCustomization: --> GK"))
            {
                killer = "Clown";
            }

            else if (line.Contains("LogCustomization: --> SD"))
            {
                killer = "Freddy";
            }

            else if (line.Contains("LogCustomization: --> DO"))
            {
                killer = "Doctor";
            }

            else if (line.Contains("LogCustomization: --> CA"))
            {
                killer = "Cannibal";
            }
            else if (line.Contains("LogCustomization: --> MM"))
            {
                killer = "Myers";
            }

            else if (line.Contains("LogCustomization: --> UK"))
            {
                killer = "Deathslinger";
            }

            else if (line.Contains("LogCustomization: --> SwedenKiller"))
            {
                killer = "Oni";
            }

            else if (line.Contains("LogCustomization: --> QK"))
            {
                killer = "Demogorgon";
            }

Пример. Текстовый файл

LogCustomization: --> TR_HEAD_03
LogCustomization: --> TR_TORSO_P01
LogCustomization: --> TR_LEGS_02
fsdfs
fsdfs
LogCustomization: --> KK_HEAD_04
LogCustomization: --> KK_BODY_P01
LogCustomization: --> KK_LEGS_P01
dfsdfs
LogCustomization: --> TW_HEAD02_LP01
LogCustomization: --> TW_BODY03_LP01
LogCustomization: --> TW_WEAPON07_P01
sfsdfs
LogCustomization: --> CM_HEAD_P01
LogCustomization: --> CM_TORSO_06 
LogCustomization: --> CM_LEGS_LP01
sdfsf
sdfsdf

Похоже, ваш пост - это в основном код; пожалуйста, добавьте более подробную информацию. Похоже, ваш пост - это в основном код; пожалуйста, добавьте подробности.

Ответы [ 2 ]

0 голосов
/ 12 июля 2020

Я бы многое изменил в вашем коде, чтобы решить эту проблему.

Во-первых, сохраните все ваши условия в Словаре, подобном этому

Dictionary<string, string> keywords = new Dictionary<string, string>{
        {"LogCustomization: --> TW", "Wraith"},
        {"LogCustomization: --> TR", "Trapper"},
        {"LogCustomization: --> Sw", "Oni"},
        ... add the other keys here ....
    };

В словаре, который вы хранить в качестве ключей все условия, которые вы хотите проверить, с помощью слова "SwedenKiller", сокращенного до двух букв. В значении словаря сохраните значение, которое вы хотите использовать при извлечении этой конкретной строки.

На этом этапе ваш код может быть значительно сокращен с помощью этого

// Load all data in memory in the variable allData
var allData = File.ReadAllLines("");

// Loop using a normal loop. This will allow to use the variable x as an indexer
// to retrieve the lines before the current one....
for (int x = 0; x < allData.Length; x++)
{
    string line = allData[x];

    // Discard the lines that doesn't start with the LogCustomization words
    if (line.StartsWith("LogCustomization: --> "))
    {
        // Take the words and two more characters
        string sub = line.Substring(0, 22);

        // Check if the substring is listed in the keywords dictionary
        if (keywords.ContainsKey(sub))
        {
            // Take the value and ....
            string killer = keywords[sub];
            if (x > 0)
            {
                // Take the previous line (x-1)
                string prevLine = allData[x - 1];
                if (x > 1)
                {
                    // Take the previous previous line (x-2)
                    string prevprevLine = allData[x - 2];

                    // Here goes your real logic with kille e prev lines.
                    Console.WriteLine($"current={line}, prev={prevLine}, prevprev={prevprevLine}");
                }
            }
        }
        
    }
}
0 голосов
/ 12 июля 2020

Я не уверен, чего вы пытаетесь достичь, вот код для получения строки с двумя предыдущими строками:

        var lines = File.ReadAllLines("DeadByDaylightCopy.log");

        for (int i = 0; i < lines.Length; i++)
        {
            var linesAnd2PreviousLines = lines[Math.Max(0, i - 2)..(i + 1)];
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...