c# - Filtering an array with duplicate elements -


i have array of fileinfo objects duplicate elements i'd filter, i.e.e remove duplicates, elements sorted last write time using custom comparer. format of file names follows:

file{number}{yyymmdd}{hhmmss}.txt

what i'd know if there's elegant way of filtering out 2 files same file number recent present in list, i.e. have 2 elements in array following file names:

file1_20110214_090020.txt

file1_20101214_090020.txt

i keep recent version of file1. code have getting files follows:

 fileinfo[] listoffiles = disearch.getfiles(filesearch);  icomparer compare = new filecomparer(filecomparer.compareby.lastwritetime);  array.sort(listoffiles, compare); 

thanks help.

update:

forgot add caveat, program in question using .net 2.0, no linq unfortunately. sorry confusion, above corrected file number same

with linq, do:

var listoffiles = disearch                   .getfiles(filesearch)                   .groupby(file => file.name.substring(file.name.indexof('_')))                   .select(g => g.orderby(file => file.lastwritetime).last())                   .toarray(); 

if want these files ordered last write-time, put in .orderbydescending(file => file.lastwritetime) before toarray call.

you of course use more efficient technique find latest file each group, such maxby operator.

edit:

in .net 2.0, construct dictionary<string, list<fileinfo>> (with key being 'file-group') array, , extract latest file each list of dictionary's values collection, produce result.

if on c# 3 or later, option use linqbridge, lets use linq objects while targeting .net 2.0.


Comments

Popular posts from this blog

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

apache - Add omitted ? to URLs -

php - How can I stop spam on my custom forum/blog? -