Filtering an array with repeating elements

I have an array of FileInfo objects with repeating elements that I would like to filter, i.e. delete duplicates; items are sorted by the last recording time using user matching. The file name format is as follows:

file {number} {} {YYYMMDD HHMMSS} .txt

What I would like to know is an elegant way to filter two files with the same file number so that only the latest one is listed, i.e. I have two elements in my array with the following file names:

file1_20110214_090020.txt

file1_20101214_090020.txt

I would like to keep the latest version of file1 . The code for getting the files is as follows:

 FileInfo[] listOfFiles = diSearch.GetFiles(fileSearch);
 IComparer compare = new FileComparer(FileComparer.CompareBy.LastWriteTime);
 Array.Sort(listOfFiles, compare);

Thank you for your help.

UPDATE:

, , , .Net 2.0, , , LINQ . , ,

+3
2

LINQ :

var listOfFiles = diSearch
                  .GetFiles(fileSearch)
                  .GroupBy(file => file.Name.Substring(file.Name.IndexOf('_')))
                  .Select(g => g.OrderBy(file => file.LastWriteTime).Last())
                  .ToArray();

, , .OrderByDescending(file => file.LastWriteTime) ToArray.

, , , MaxBy.

.NET 2.0 Dictionary<string, List<FileInfo>> ( , " " ) , Values, .

# 3 , LINQBridge, LINQ to Objects .NET 2.0.

+5

, , (YYYYMMM ..), . :

var mostRecentFiles = listOfFiles.GroupBy( f => f.Name.Substring(0, f.Name.IndexOf("_")))
                                 .Select( g => g.OrderByDescending( f => 
                                         { string[] s =f.Name.Split(new [] {'_', '.'}); return Convert.ToDecimal(s[1]+s[2]);}).First())
                                 .ToList();
0

Source: https://habr.com/ru/post/1792921/


All Articles