You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何用.split解析文件名实现1分钟间隔同列车图片配对展示

列车图片配对展示实现方案

核心实现逻辑

  • 先解析所有图片文件名,提取列车ID、拍摄时间结构化元数据,过滤格式不符合规范的无效文件
  • 按列车ID对图片分组,仅在同列车的图片范围内做时间匹配
  • 每组内图片按拍摄时间升序排列,遍历查找时间间隔为1分钟的图片对,配对成功的两张图相邻插入最终展示列表
  • 未找到配对的单张图片,按拍摄时间顺序追加到展示列表中

难点问题解决方法

1. 文件名Split解析方法

不要直接对完整文件路径做分割,先通过Path.GetFileNameWithoutExtension()拿到去掉扩展名的纯文件名,再用_作为分隔符调用Split方法,按索引取对应字段:

  • 索引0:小时字段
  • 索引1:分钟字段
  • 索引2:秒字段
  • 索引3:带id前缀的列车ID字段,截取前2位后即可拿到纯列车ID
    解析时增加格式校验,避免文件名不规范导致的运行时报错。

2. 1分钟间隔校验逻辑

不要直接对比分钟字段差值(会出现跨小时判断错误,比如10:59和11:00的1分钟间隔无法识别),将时、分、秒转为TimeSpan类型的时间点,计算两个时间点的秒级差值,和60秒做对比即可:

  • 允许根据实际拍摄偏差设置误差阈值(比如5秒,即差值在55-65秒区间都判定为间隔1分钟)
  • 自动兼容跨小时、跨零点的时间间隔判断

完整实现代码

// 图片元数据结构,C#版本低于9.0可把record替换为class
public record PhotoInfo
{
    public string FilePath { get; set; }
    public string TrainId { get; set; }
    public TimeSpan ShootTime { get; set; }
    public bool IsPaired { get; set; } = false;
}

// 原有逻辑改造
var photoPathList = new List<string>();
var now = DateTime.Now;
int day = (int)now.DayOfWeek;

var appFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
var fotosFolder = await appFolder.GetFolderAsync("Assets\\Fotos");
var dayFolders = await fotosFolder.GetFoldersAsync();
var firstDayFolder = dayFolders[day];
var allFotos = await firstDayFolder.GetFilesAsync();

var photoMetaList = new List<PhotoInfo>();
foreach (var photo in allFotos)
{
    // 拿到无扩展名的纯文件名
    string fileNameWithoutExt = Path.GetFileNameWithoutExtension(photo.Name);
    // 按下划线分割字段,自动忽略空片段
    string[] fileParts = fileNameWithoutExt.Split('_', StringSplitOptions.RemoveEmptyEntries);
    // 校验文件名格式合法性,不合法的文件直接跳过
    if (fileParts.Length != 4 
        || !fileParts[3].StartsWith("id")
        || !int.TryParse(fileParts[0], out int hour)
        || !int.TryParse(fileParts[1], out int minute)
        || !int.TryParse(fileParts[2], out int second))
    {
        continue;
    }
    // 组装元数据
    photoMetaList.Add(new PhotoInfo
    {
        FilePath = photo.Path,
        TrainId = fileParts[3].Substring(2), // 去掉id前缀取真实列车ID
        ShootTime = new TimeSpan(hour, minute, second)
    });
}

var finalShowList = new List<string>();
// 按列车ID分组
var trainPhotoGroups = photoMetaList.GroupBy(p => p.TrainId);
foreach (var group in trainPhotoGroups)
{
    // 组内按拍摄时间升序排序
    var sortedPhotos = group.OrderBy(p => p.ShootTime).ToList();
    for (int i = 0; i < sortedPhotos.Count; i++)
    {
        if (sortedPhotos[i].IsPaired) continue;
        // 查找间隔1分钟的配对图片,误差阈值设为5秒,可根据业务调整
        var matchTarget = sortedPhotos.Skip(i + 1)
            .FirstOrDefault(p => 
                !p.IsPaired 
                && Math.Abs((p.ShootTime - sortedPhotos[i].ShootTime).TotalSeconds - 60) <= 5
            );
        if (matchTarget != null)
        {
            // 配对成功,两张图相邻加入列表
            finalShowList.Add(sortedPhotos[i].FilePath);
            finalShowList.Add(matchTarget.FilePath);
            sortedPhotos[i].IsPaired = true;
            matchTarget.IsPaired = true;
        }
        else
        {
            // 无配对,单张加入列表
            finalShowList.Add(sortedPhotos[i].FilePath);
            sortedPhotos[i].IsPaired = true;
        }
    }
}

showPhotosEL.ItemsSource = finalShowList;

提示:如果业务要求严格匹配整1分钟间隔无误差,把代码里的误差阈值从5改成0即可。


内容的提问来源于stack exchange,提问作者AvaRomeo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 21:01:15