How to find the maximum value of Item2 in Tuple <string, DateTime>

Ok, I did it before, but I draw a space, so I hope that the big brains here on SO can help me.

I have Tuple<string, DateTime>where the line is FileName, and DateTime is the last date that this file was sent by the process. The file names will not be identical, but they all confirm some kind of file mask (for example, I can have several entries where it stringmatches the file mask "????AD??"). I want to find the latest one DateTimefor a given file mask.

I can’t remember how I solved this problem before, and the previous employer had it, so I can’t even cannibalize my old code. Any help would be greatly appreciated.

Clarification (as this may be a little dumb)

Given:

(0501AD01, 5/2/2010)
(0502AD02, 5/3/2010)
(0503AD03, 5/4/2010)
<snip>
(0803AD99, 8/4/2010)
(0804AD00, 8/5/2010)
(0805AD01, 8/6/2010)

I want to return 8/6/2010

+5
source share
2 answers

So, you tupleshave IEnumerable<Tuple<string, DateTime>>, and you have fileMask, and you have a method

bool MatchesFileMask(FileMask fileMask, string filename)

which returns trueif filenamematches the file mask fileMask. Then you can say:

var mostRecent = tuples.Where(x => MatchesFileMask(fileMask, x.Item1)
                       .Max(x => x.Item2);
+8
source

A slice of cake with LINQ:

var data = new List<Tuple<string, DateTime>>(); // add some data

var maxTimestamp = data.Where(t => MatchesFileMask(t.Item1)).Max(t => t.Item2);

Of course, I deceived, assuming that the predicate already written MatchesFileMask, but it is not too difficult to make a regular expression from a simple mask in the style of a globe:

var mask = "????AD??";
var regex = new Regex(mask.Replace('?', '.').Replace("*", ".*"));
var predicate = new Func<string, bool>(regex.IsMatch);

var maxTimestamp = data.Where(t => predicate(t.Item1)).Max(t => t.Item2);
+6
source

All Articles