MSU
MSU

Reputation: 415

How to read a csv or text file using c# and count characters line by line of that file and show if less than 1500?

I want to read a csv or text file using c# and count characters line by line of that file and show at the end of the line of which character count is less than 1500? I can count total number of characters, but i can't count characters of line by line...It may be a silly question to the C# experts, but i just started coding in c#, i would also love to know what is the best way to be a proficient c# coder???

Upvotes: 1

Views: 1798

Answers (3)

BryanJ
BryanJ

Reputation: 8563

I took your question to mean you want to know at which line is the total character count of the document less than 1500:

        string[] lines = File.ReadAllLines("filename.txt");
        int count = 0;
        int line = 0;

        for (; line < lines.Length; line++)
        {
            count += lines[line].Length;
            if (count >= 1500)
            {
                // previous line is < 1500
                Console.WriteLine("Character count < 1500 on line {0}", line - 1);
                Console.WriteLine("Line {0}: {1}", line - 1, lines[line - 1]);
                break;
            }
        }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503669

I'd use LINQ:

var shortLines = File.ReadLines("file.csv")
                     .Where(line => line.Length < 1500);

foreach (var line in shortLines)
{
    // Do whatever you need to
}

Note that this will only read the file when you iterate over shortLines, and it will stream it - but it does mean that if you iterate over shortLines twice, it'll read it twice. If you need to iterate over those lines more than once, call ToList after Where.

Upvotes: 3

paul
paul

Reputation: 22021

string completeFile = File.ReadAllText("c:\temp\somefile.txt");

string[] arrayOfLines = completeFile.Split('\n');

foreach(string singleLine in arrayOfLines)
{
    //count
}

Upvotes: 0

Related Questions