Bird
Raised Fist0

You want to read a text file and count how many lines contain the word "error" (case insensitive). Which code snippet correctly does this?

hard🚀 Application Q15 of Q15
C Sharp (C#) - File IO
You want to read a text file and count how many lines contain the word "error" (case insensitive). Which code snippet correctly does this?
Avar lines = File.ReadAllLines("log.txt"); int count = 0; foreach(var line in lines) { if(line.Contains("error")) count++; }
Bstring content = File.ReadAllText("log.txt"); int count = content.Split('\n').Count(line => line.Contains("error"));
Cvar lines = File.ReadAllLines("log.txt"); int count = lines.Count(line => line.ToLower().Contains("error"));
Dstring[] lines = File.ReadAllText("log.txt").Split('\n'); int count = lines.Count(line => line.Contains("error"));
Step-by-Step Solution
Solution:
  1. Step 1: Choose method to read lines

    File.ReadAllLines returns an array of lines, perfect for line-by-line processing.
  2. Step 2: Count lines with "error" case-insensitive

    var lines = File.ReadAllLines("log.txt"); int count = lines.Count(line => line.ToLower().Contains("error")); converts each line to lowercase and checks if it contains "error", then counts matches using LINQ.
  3. Step 3: Check other options

    string content = File.ReadAllText("log.txt"); int count = content.Split('\n').Count(line => line.Contains("error")); uses ReadAllText but misses case-insensitive check. var lines = File.ReadAllLines("log.txt"); int count = 0; foreach(var line in lines) { if(line.Contains("error")) count++; } misses case-insensitive check. string[] lines = File.ReadAllText("log.txt").Split('\n'); int count = lines.Count(line => line.Contains("error")); incorrectly assigns ReadAllText to string array without ToLower.
  4. Final Answer:

    var lines = File.ReadAllLines("log.txt"); int count = lines.Count(line => line.ToLower().Contains("error")); -> Option C
  5. Quick Check:

    Use ReadAllLines + ToLower + Count for case-insensitive search [OK]
Quick Trick: Use ReadAllLines and ToLower for case-insensitive line checks [OK]
Common Mistakes:
MISTAKES
  • Ignoring case sensitivity
  • Using ReadAllText but treating as array
  • Not converting lines to lowercase

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes