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

C#如何查找列表中属性值匹配的所有索引(解决内存占用问题)

解决方法

List.FindIndex() 只会返回第一个匹配元素的索引,要获取所有匹配指定ticker的元素索引,可以通过LINQ结合索引筛选实现,同时完成保留15条数据的清理逻辑,代码如下:

public static void CleanTrackers()
{
    foreach (var ticker in tickersToWatchForAHPM)
    {
        // 筛选出所有匹配当前ticker的元素索引
        var matchingIndices = QouteTrackers
            .Select((tracker, index) => new { Tracker = tracker, Index = index })
            .Where(x => x.Tracker.Ticker == ticker)
            .Select(x => x.Index)
            .ToList();

        // 若匹配条目超过15条,删除多余部分(保留最新的15条)
        if (matchingIndices.Count > 15)
        {
            // 逆序删除,避免删除时索引偏移导致的错误
            var indicesToRemove = matchingIndices.Take(matchingIndices.Count - 15)
                                                 .OrderByDescending(i => i);
            foreach (var index in indicesToRemove)
            {
                QouteTrackers.RemoveAt(index);
            }
        }
    }
}

关键说明

  • 使用Select((item, index))可以同时获取集合元素和对应的索引,再通过Where筛选出目标ticker的所有索引。
  • 逆序删除是核心:如果正序删除元素,前面的元素被移除后,后续元素的索引会发生偏移,导致删除位置错误;逆序从后往前删除则不会出现这个问题。
  • 代码中默认保留最后15条匹配数据(假设你的集合是按时间顺序新增,最新数据在末尾),如果需要保留最早的15条,只需将Take(matchingIndices.Count - 15)替换为Skip(15)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:57:02