Reading the next line using LINQ and File.ReadAllLines ()

I have a file that represents elements, on one line there is a GUID clause followed by 5 lines describing the element.

Example:

Line 1: Guid=8e2803d1-444a-4893-a23d-d3b4ba51baee name= line1 
Line 2: Item details = bla bla   
.  
.  
Line 7: Guid=79e5e39d-0c17-42aa-a7c4-c5fa9bfe7309 name= line7 
Line 8: Item details = bla bla    
.  
. 

First I try to get this file in order to get the GUIDs of elements that match the criteria provided by LINQ, for example. where line.Contains ("line1") .. Thus, I will get the whole line, I will extract the GUID from it, I want to pass this GUID to another function, which should access the file "again", find this line (where line.Contains("line1") && line.Contains("8e2803d1-444a-4893-a23d-d3b4ba51baee")it reads next 5 lines starting from this line.

Is there an effective way to do this?

+3
2

LINQ, . , Enumerable GetEnumerator :

public IEnumerable<LogData> GetLogData(string filename)
{
    var line1Regex = @"Line\s(\d+):\sGuid=([0123456789abcdefg]{8}-[0123456789abcdefg]{4}-[0123456789abcdefg]{4}-[0123456789abcdefg]{4}-[0123456789abcdefg]{12})\sname=\s(\w*)";
    int detailLines = 4;

    var lines = File.ReadAllLines(filename).GetEnumerator();
    while (lines.MoveNext())
    {
        var line = (string)lines.Current;
        var match = Regex.Match(line, line1Regex);
        if (!match.Success)
             continue;

        var details = new string[detailLines];
        for (int i = 0; i < detailLines && lines.MoveNext(); i++)
        {
            details[i] = (string)lines.Current;
        }

        yield return new LogData
        {
            Id = new Guid(match.Groups[2].Value),
            Name = match.Groups[3].Value,
            LineNumber = int.Parse(match.Groups[1].Value),
            Details = details
        };
    }
}
+2

, LINQ , , , , . - , . , , :

    private void GetStuff()
    {
        var lines = File.ReadAllLines("foo.txt");
        var result = new Dictionary<Guid, String[]>();
        for (var index = 0; index < lines.Length; index += 6)
        {
            var item = new
            {
                Guid = new Guid(lines[index]),
                Description = lines.Skip(index + 1).Take(5).ToArray()
            };
            result.Add(item.Guid, item.Description);
        }
    }
+3

Source: https://habr.com/ru/post/1734822/


All Articles