From 5ed701343f482ca9d29c367796169ac3a8619309 Mon Sep 17 00:00:00 2001 From: ema Date: Wed, 14 Jan 2026 13:58:56 +0800 Subject: [PATCH] Refactor GetNearestLrc for clarity and efficiency #1858 Simplified the logic in GetNearestLrc by using clearer LINQ queries and reducing redundant operations. The method now directly finds the latest timestamp not greater than the specified time, merges duplicate timestamps if necessary, and returns the appropriate LrcLine. --- .../LyricTrack/LrcHelper.cs | 32 ++++++++----------- 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/LyricTrack/LrcHelper.cs b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/LyricTrack/LrcHelper.cs index 278605a..ce0c943 100644 --- a/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/LyricTrack/LrcHelper.cs +++ b/QuickLook.Plugin/QuickLook.Plugin.VideoViewer/LyricTrack/LrcHelper.cs @@ -123,28 +123,24 @@ public static class LrcHelper /// The nearest at or before the specified time, or null if none found. public static LrcLine GetNearestLrc(IEnumerable lrcList, TimeSpan time, string separator = "\n") { - IEnumerable lines = lrcList - .Where(x => x.LrcTime != null && x.LrcTime <= time) - .OrderByDescending(x => x.LrcTime); + // Use LINQ to filter valid candidates + List candidates = [.. lrcList.Where(x => x.LrcTime != null && x.LrcTime <= time)]; - LrcLine first = lines.FirstOrDefault(); + if (!candidates.Any()) + return null; - if (first is not null) - { - LrcLine[] mergingLines = [.. lines.Where(x => x.LrcTime == first.LrcTime)]; + // Find the latest timestamp not greater than the specified time + TimeSpan? nearestTime = candidates.Max(x => x.LrcTime); - // If any duplicate timestamps exist, merge them - if (mergingLines.Length > 1) - { - // Create a new LrcLine can keep original ones unchanged - return new LrcLine( - first.LrcTime, - string.Join(separator, lines.Where(x => x.LrcTime == first.LrcTime).Select(x => x.LrcText)) - ); - } - } + // Get all lines with the latest timestamp (could be multiple if there are duplicate timestamps) + LrcLine[] nearestLines = [.. candidates.Where(x => x.LrcTime == nearestTime)]; - return first; + // If only one line matches, return the original object + if (nearestLines.Length == 1) + return nearestLines.First(); + + // Otherwise, merge texts and create a new LrcLine to keep original ones unchanged + return new LrcLine(nearestTime, string.Join(separator, nearestLines.Select(x => x.LrcText))); } ///