Reputation: 125414
I need to filter files in a directory based on a date in the file name.
The name has four groups of numbers:
9999.99999.201305021219.99999999.txt
When there is more than one file with the second group of numbers repeated I want to use the newer one based on the date on the third group of numbers (YYYYMMDDHHMM).
If there are these files in the directory:
1 1100.04037.201305090945.04542592.TXT
2 1100.04041.201305091108.04542707.TXT
3 1100.04041.201305091117.60563353.TXT
4 1100.04047.201305080942.04541666.TXT
5 1100.24084.201305021658.04539125.TXT
6 1100.24084.201305061731.04540560.TXT
I want those in the lines 2 and 5 to be discarded. This is how I managed to iterate over the directory files:
public static void Main(string[] args)
{
string directory = @"\\some\net\path";
string[] arquivos = Directory.GetFiles(directory, "1100.*.txt", SearchOption.TopDirectoryOnly);
foreach (string arquivo in arquivos)
{
Console.WriteLine(arquivo.Substring(directory.Length + 1));
}
Console.ReadLine();
}
Upvotes: 2
Views: 945
Reputation: 4173
var ci = CultureInfo.InvariantCulture;
// first, parse your input files:
var parsed =
from f in arquivos
let c = Path.GetFileName(f).Split('.')
select new
{
Key = c[1],
Name = f,
Date = DateTime.ParseExact(c[2], "yyyyMMddHHmm", ci)
};
// now, group by file id, and order by file date,
// picking record by latest date:
var result =
parsed.GroupBy(g => g.Key)
.Select(t => t.OrderByDescending(z => z.Date)
.Select(z => z.Name).First()).ToList();
Upvotes: 1
Reputation: 35363
var files = arquivos
.Select(f => new{OrgName = f, Parts = new FileInfo(f).Name.Split('.')})
.GroupBy(x=>x.Parts[1])
.Select(g=>g.OrderByDescending(x=>x.Parts[2]).First().OrgName);
foreach (string arquivo in files)
{
.....
}
Upvotes: 3
Reputation: 21167
Depending on how many files are in the directory I'd suggest using a Dictionary to hold your values as you iterate through the folder. You can use the 2nd group of numbers as the key and then check to see if the key is already present in the dictionary. If it is, you can perform whatever comparison fits in order to determine which one you keep.
Upvotes: 2