When it comes to iterating over collections in C#, the performance difference between foreach and for loops primarily depends on the collection type being traversed.
For arrays and Lists, a traditional for loop with indexing can be marginally faster because it avoids the overhead of creating an enumerator object, especially in performance-critical scenarios.
The foreach loop internally creates an IEnumerator, which adds a small memory allocation and method call overhead.
However, for most modern applications, this performance difference is negligible and often optimized away by the JIT compiler.
The readability benefits of foreach typically outweigh the minor performance gains of for loops in non-critical code paths.
Collections like LinkedList or those implementing only IEnumerable actually perform better with foreach since they don't support efficient random access.
The rule of thumb: use foreach for readability in most cases, and only switch to for loops when benchmarking shows a meaningful performance improvement in your specific high-performance scenarios.
Example
// Collection to iterate List<int> numbers = Enumerable.Range(1, 10000).ToList(); // Using for loop public void ForLoopExample(List<int> items) { int sum = 0; for (int i = 0; i < items.Count; i++) { sum += items[i]; } // For loop can be slightly faster for List<T> and arrays // because it avoids creating an enumerator } // Using foreach loop public void ForEachLoopExample(List<int> items) { int sum = 0; foreach (int item in items) { sum += item; } // More readable and works well for any collection type // Preferred for most scenarios where performance isn't critical } // For a LinkedList, foreach is typically faster public void LinkedListExample(LinkedList<int> linkedItems) { int sum = 0; // This would be inefficient with a for loop since LinkedList // doesn't support efficient indexing foreach (int item in linkedItems) { sum += item; } }
Raw string literals in C# provide a flexible way to work with multiline strings, with some interesting rules around how quotes work.
The key insight is that you can use any number of double quotes (three or more) to delimit your string, as long as the opening and closing sequences have the same number of quotes.
"""
// Three quotes - most common usage string basic = """ This is a basic multiline string """; // Four quotes - when your content has three quotes string withThreeQuotes = """" Here's some text with """quoted""" content """"; // Five quotes - when your content has four quotes string withFourQuotes = """"" Here's text with """"nested"""" quotes """""; // Six quotes - for even more complex scenarios string withFiveQuotes = """""" Look at these """""nested""""" quotes! """""";
The general rule is that if your string content contains N consecutive double quotes, you need to wrap the entire string with at least N+1 quotes. This ensures the compiler can properly distinguish between your content and the string's delimiters.
// Example demonstrating the N+1 rule string example1 = """ No quotes inside """; // 3 quotes is fine string example2 = """" Contains """three quotes""" """"; // Needs 4 quotes (3+1) string example3 = """"" Has """"four quotes"""" """""; // Needs 5 quotes (4+1)
// Indentation example string properlyIndented = """ { "property": "value", "nested": { "deeper": "content" } } """; // This line's position determines the indentation
This flexibility with quote counts makes raw string literals extremely versatile, especially when dealing with content that itself contains quotes, like JSON, XML, or other structured text formats.
When working with SQL Server, you may often need to count the number of unique values in a specific column. This is useful for analyzing data, detecting duplicates, and understanding dataset distributions.
To count the number of unique values in a column, SQL Server provides the COUNT(DISTINCT column_name) function. Here’s a simple example:
COUNT(DISTINCT column_name)
SELECT COUNT(DISTINCT column_name) AS distinct_count FROM table_name;
This query will return the number of unique values in column_name.
column_name
If you need to count distinct combinations of multiple columns, you can use a subquery:
SELECT COUNT(*) AS distinct_count FROM (SELECT DISTINCT column1, column2 FROM table_name) AS subquery;
This approach ensures that only unique pairs of column1 and column2 are counted.
column1
column2
By leveraging COUNT(DISTINCT column_name), you can efficiently analyze your database and extract meaningful insights. Happy querying!
When working with large files, reading the entire file at once may be inefficient or unnecessary, especially when you only need the first few lines.
In C#, you can easily read just the first N lines of a file, improving performance and resource management.
Reading only the first few lines of a file can be beneficial for:
Here's a simple and efficient method using C#:
using System; using System.IO; class FileReader { /// <summary> /// Reads the first N lines from a file. /// </summary> /// <param name="filePath">The path to the file.</param> /// <param name="numberOfLines">Number of lines to read.</param> /// <returns>Array of strings containing the lines read.</returns> public static string[] ReadFirstNLines(string filePath, int numberOfLines) { List<string> lines = new List<string>(); using (StreamReader reader = new StreamReader(filePath)) { string line; int counter = 0; // Read lines until the counter reaches numberOfLines or EOF while (counter < numberOfLines && (line = reader.ReadLine()) != null) { lines.Add(line); counter++; } } return lines.ToArray(); }
Here's a practical example demonstrating the usage of the method above:
string filePath = "C:\\largefile.txt"; int linesToRead = 10; string[] firstLines = FileReader.ReadFirstNLines(filePath, firstLinesCount); foreach (string line in firstLines) { Console.WriteLine(line); }
For a concise implementation, LINQ can also be used:
using System; using System.IO; using System.Linq; class FileReader { public static IEnumerable<string> ReadFirstNLines(string filePath, int numberOfLines) { // Take first N lines directly using LINQ return File.ReadLines(filePath).Take(numberOfLines); } }
string path = "C:\\largeFile.txt"; int n = 10; var lines = FileReader.ReadFirstNLines(path, n); foreach (string line in lines) { Console.WriteLine(line); }
File.ReadLines
File.ReadAllLines
ReadAllLines()
By limiting your reading operations to only the first few lines you actually need, you significantly enhance your application's efficiency and resource management.
Register for my free weekly newsletter.