Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Count() to FileInfo #22

Closed
adamfisher opened this issue Dec 27, 2018 · 2 comments
Closed

Add Count() to FileInfo #22

adamfisher opened this issue Dec 27, 2018 · 2 comments
Assignees

Comments

@adamfisher
Copy link
Contributor

This issue is a proposal to add Count() to FileInfo to provide the ability to count the total number of lines in a file (no filter specified) or count the specific number of occurrences of a string in a file (using the filter).

/// <summary>
/// Gets the total number of lines in a file.
/// Note this method is optimized for large files and must count each line so it may be expensive for large files.
/// </summary>
/// <param name="this">The file to perform the count on.</param>
/// <param name="filter">If specified, finds the number of concurrences of the string in the file.</param>
/// <returns>
/// A count of the number of lines in the file.
/// </returns>
public static long Count(this FileInfo @this, string filter = null)
{
	using (var reader = @this.OpenText())
	{
		var count = 0L;

		if (filter == null)
		{
			while (!reader.EndOfStream)
			{
				reader.ReadLine();
				count++;
			}
		}
		else
		{
			while (!reader.EndOfStream)
			{
				var line = reader.ReadLine();

				if(line != null && line.Contains(filter))
					count++;
			}
		}

		return count;
	}
}
@JonathanMagnan JonathanMagnan self-assigned this Dec 28, 2018
@JonathanMagnan
Copy link
Member

Hello @adamfisher ,

We are now back from holiday and started to look at your suggestion.

For the name

We will probably go with the following name:

  • CountLines()

For the code

  • We will probably go to a solution similar to this one: https://stackoverflow.com/a/119572/5619143
  • The filter/predicate will probably instead be a Func<string, bool>, so people will be able to apply any kind of predicate

We will try to add it this weekend.

@JonathanMagnan
Copy link
Member

Hello @adamfisher ,

The v2.1.1 has been released with this extension methods.

Let me know if everything works as expected.

Best Regards,

Jonathan

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants