开发者

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

开发者 https://www.devze.com 2023-03-03 02:50 出处:网络
Okay, I\'ve done this before, but I\'m drawing a blank, so I\'m hoping the big brains here on SO can bail me out.

Okay, I've done this before, but I'm drawing a blank, so I'm hoping the big brains here on SO can bail me out.

I have a Tuple<string, DateTime> where the string is a FileName and the DateTime is the last date that file was sent by a process. The FileNames will not be identical, but they all confirm to a filemask of some kind (for instance, I might have several entries where the string conforms to file mask "????AD??"). I want to find the most recent DateTime for a given filemask.

I can't remember how I resolved this problem before, and it was at a previous employer, so I can't even cannibalize my old code. Any help would be greatly appreciated.

Clarification (since this could be a little obtuse)

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


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

bool MatchesFileMask(FileMask fileMask, string filename)

that returns true if filename matches the file mask fileMask. Then you can say:

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


Piece 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 cheated by assuming there's a MatchesFileMask predicate already written, but it's not too hard to make a regex out of a simple glob-style mask:

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号