简体   繁体   English

C#-获取列表中最接近的大数

[英]C# - Get closest greater number in a list

I have an unsorted list of subtitle lines which looks like this: 我有一个未排序的字幕行列表,看起来像这样:

public class SubtitleItem{
        public int StartTime { get; set; } //In milliseconds
        public int EndTime { get; set; } //This too
        ...
}

Let's say the video's current position is at 1000ms and there are three subtitle lines which starts at 900ms, 1200ms, and 1300ms. 假设视频的当前位置是1000毫秒,并且有3条字幕行,分别从900毫秒,1200毫秒和1300毫秒开始。 I want the second line. 我要第二行。 Since I cannot perfectly sync the video position, I need to get the closest subtitle line which starts after the current video position. 由于无法完全同步视频位置,因此需要获得最接近的字幕行,该字幕行应位于当前视频位置之后。

Note: I sync every 100ms. 注意:我每100毫秒同步一次。

You can do this using Linq. 您可以使用Linq执行此操作。

Assuming your subtitles are in something which implements IEnumerable and the current time is in a var named currentTime you can do: 假设您的字幕位于实现IEnumerable的某项中,并且当前时间位于名为currentTime的var中,则可以执行以下操作:

var subtitle = (from subtitle in subtitles
                let diff = subtitle.StartTime - currentTime
                where diff > 0
                order by diff).FirstOrDefault();
    var nextSubtitle = subtitles.OrderBy(i=> i.StartTime)
                       .Where(i=> i.StartTime > currentTime).FirstOrDefault();
public SubtitleItem GetNextSubtitle(int currentPosition, List<SubtitleItem> items)
{
    return items.OrderBy(i => i.StartTime).First(i => i.StartTime > currentPosition);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM