Reputation: 8768
Firstly, I have a helper method that will return the number of files in a list that have a given extension. I want to get the number of audio files overall in a given list, and I have a list of the audio extensions used.
public List<string> accepted_extensions = {"mp3", "wav", "m4a", "wma", "flac"};
Helper method:
private int getFileTypeCount(string[] files, string ext)
{
int count = 0;
foreach (string file in files) if (Path.GetExtension(file).Contains(ext))
{
count++;
}
return count;
}
So, I wanted to see if it was possible to write a ForEach with LINQ that would add teh result of each method with a list and the given extension to an integer. I'm not very good with LINQ, so I started with:
int audio_file_count = accepted_extensions.ForEach(i => getFileTypeCount(new_file_list.ToArray(),i));
but I'm not sure how to go about adding the number returned by the helper method to a total. I know this could easily be done with a regular foreach loop, I was just interested o see if it was possible with LINQ.
Upvotes: 1
Views: 916
Reputation: 35353
var count = files
.Count(f => accepted_extensions.Any(x => Path.GetExtension(f).EndsWith(x)));
Upvotes: 0
Reputation: 20575
static void Main(string[] args)
{
List<string> accepted_extensions = new List<string> {".mp3", ".wav", ".m4a", ".wma", ".flac"};
string[] files = new string[] {};
int count = files.Count(file => accepted_extensions.Contains(Path.GetExtension(file)));
}
Upvotes: 0
Reputation: 23675
You could try this:
Int32 count = files.Count(file => Path.GetExtension(file).Contains(ext));
Upvotes: 0
Reputation: 8459
You can use the Sum
method. Modify your query in this way:
int audio_file_count = accepted_extensions.
Sum(extension => getFileTypeCount(new_file_list.ToArray(), extension));
Upvotes: 2
Reputation: 1038730
You could use the .Count()
extension method to perform an aggregation over the resultset:
private int GetFileTypeCount(string[] files, string ext)
{
return files.Count(file => Path.GetExtension(file).Contains(ext));
}
Upvotes: 3