Share via

Converting a text file to data table

George Tyrebyter 46 Reputation points
Jan 4, 2023, 8:00 PM

I have the following as a plain text file:
============> Load case 1 <================== Pass 1 ==================================
Sig1 Sig2 Sig3 Tau1 Tau2 Tau3 Equiv Max Delta % ERROR
57.0475 -1345.72 -526.794 584.008 0.00000 0.00000 -1585.19 2D
10.9000 54.5000 405.300 -17.3000 704.200 -90.6000 1285.87 3D ACT
6.21902 -53.8767 407.467 -13.3438 676.727 -86.3312 1259.17 3D PRED 108.38 8.4282

The block above repeats with a similar header with Load case 2, and the related Sig1, Sig2 etc.

My question is, the only real needed data is what is that under the column named "Max Delta" Is it better to create a C# DataTable or use a different constrict? The data I'm focused on is after "3D PRED" 108.38. It is under the column "Max Delta" I add this in case the information doesn't appear correct.

Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,363 questions
{count} votes

Accepted answer
  1. Jack J Jun 25,286 Reputation points Microsoft External Staff
    Jan 6, 2023, 6:14 AM

    @George Tyrebyter , Welcome to Microsoft Q&A,

    One way I was thinking of processing the text file would be to look for each line that has "3D PRED" and take the value to right of it which follows.

    According to your latest description, you could try to use the following code to get what you wanted.

     string []lines = File.ReadAllLines("test.txt");  
                List<string> list = new List<string>();  
                foreach (var item in lines)  
                {  
                    if(item.Contains("3D PRED"))  
                    {  
                        int index = item.IndexOf("3D PRED");  
                          
                        string []result = item.Substring(index+ "3D PRED".Length).Split(' ').Where(i=>!string.IsNullOrEmpty(i)).ToArray();  
                        list.Add(result[0]);  
                    }  
                }  
                list.ForEach(i => Console.WriteLine(i));  
    

    txt file and result:

    276757-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Michael Taylor 57,971 Reputation points
    Jan 4, 2023, 8:24 PM

    If you literally just need the floating point values for max delta then a data table seems like overkill. Just create a List<double> and put the values in their.

       var maxDelta = new List<double>();  
       // for each row containing data  
       // delta = get data from row  
       maxDelta.Add(delta);  
    

    The harder part is reading that file but that is independent of whether you use a datatable or some other structure as nothing will support your text file out of the box. For your text file I think you're going to want to use a delimited text file reader library. You can specify that the delimiter is whitespace to read the rows in. However I think the load case blocks may cause issues so you might need to pre-parse the file to remove the header rows and then run it through a file reader library. Depending upon what file reader library you end up using will more likely impact the final structure you end up getting back containing the data. Some libraries return "data row" like dictionaries that you then query for the column directly by name. Other libraries may ask you to provide your own type and the mapping between your type's properties and the columns.

    So I would start by identifying what library you want to use to read the file (or write your own) and then determine what structure works best for that library to get the final data back you need.

    0 comments No comments

  2. Karen Payne MVP 35,556 Reputation points
    Jan 5, 2023, 10:44 AM

    In regards to reading the file, consider a finite state machine.

    Simple example

    internal partial class Program  
    {  
        static void Main(string[] args)  
        {  
            List<double> list = new List<double>();  
            foreach (string line in StateReader(@"TextFile2.txt"))  
            {  
                if (!line.StartsWith("Sig1"))  
                {  
                    var parts = line.Split(' ');  
                    if (double.TryParse(parts[6], out var value))  
                    {  
                        list.Add(value);  
                    }  
                    else  
                    {  
                        // failed to convert  
                    }  
                }  
            }  
      
            foreach (var item in list)  
            {  
                Console.WriteLine(item);  
            }  
      
            Console.ReadLine();  
        }  
      
        private static IEnumerable<string> StateReader(string fileName)  
        {  
            bool isMarker = false;  
            var lines = File.ReadLines(fileName).ToList();  
            foreach (string line in lines)  
            {  
                isMarker = true;  
                if (line.StartsWith("============>"))  
                {  
                    isMarker = !isMarker;  
                }  
                else if (isMarker)  
                {  
                    yield return line;  
                }  
            }  
        }  
    }  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.