Reputation: 9960
I have a directory with a list of file names.
VAH007157100-pic1.jpg
VAH007157100-pic2.jpg
VAH007157100-pic3.jpg
WAZ009999200-pic1.jpg
WAZ009999200-pic2.jpg
WAZ009999200-pic3.jpg
I want to know the distinct count of substringing (0, 12).
This isn't working for some reason:
string[] originalFiles = Directory.GetFiles(SelectedDirectory);
private int GetDistinctPolicyCountInDirectory()
{
var prefixes = originalFiles
.GroupBy(x => x.Substring(0, 12))
.Select(y => new { Policy = y.Key, Count = y.Count() });
return prefixes.Count();
}
I keep getting 0. Am I missing anything here?
Please note that I do not want to do a split to get the numbers separated. I want to do it by substringing.
UPDATE -
private int GetDistinctPolicyCountInDirectory(string[] originalFiles)
{
var count = originalFiles.Distinct(x => Path.GetFileName(x).Substring(0, 12)).Count();
return Convert.ToInt32(count);
}
I'm running into an error here where it says: Error 1 Cannot convert lambda expression to type 'System.Collections.Generic.IEqualityComparer' because it is not a delegate type
Upvotes: 1
Views: 1121
Reputation: 41569
I'd just consider using .Distinct()
.
Also you need to strip it down to just the filename instead of the full file path.
originalFiles.Select(x => Path.GetFileName(x).Substring(0, 12))
.Distinct().Count();
Upvotes: 6
Reputation: 41243
GetFiles
returns an array of file names with full paths, including the directory. You want to compare only the file name, so you should consider using Path.GetFileName
.
GroupBy(x => Path.GetFileName(x).Substring(0, 12));
Upvotes: 2