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

C# 如何为List<object>中与已有字符串对应的百分比数值累加

问题解决方案

基于现有代码的修改方案

你可以通过List<string>.IndexOf()方法获取重复名称在reasonsName中的下标,两个平行列表下标一一对应,即可定位到需要累加的百分比位置,修改后代码如下:

List<object> reasonsPercent = new List<object>();
List<string> reasonsName = new List<string>();

foreach (var item in lvShareRateListSorted)
{
    string reasonName = item.EventReasonTitle;
    if (reasonsName.Contains(reasonName))
    {
        // 获取重复名称对应的下标
        int index = reasonsName.IndexOf(reasonName);
        // 按你实际的数值类型做转换,此处假设TotalPercent是decimal类型
        decimal existingPercent = Convert.ToDecimal(reasonsPercent[index]);
        reasonsPercent[index] = existingPercent + Convert.ToDecimal(item.TotalPercent);
    }
    else
    {
        reasonsName.Add(reasonName);
        reasonsPercent.Add(item.TotalPercent);
    }
}

更推荐的优化方案

维护两个平行列表很容易出现索引不匹配的问题,你可以直接用Dictionary<string, decimal>(根据你TotalPercent的实际类型调整值的泛型类型)实现需求,该数据结构天然保证键(即原因名称)唯一,适合你的去重求和场景:

Dictionary<string, decimal> reasonPercentDict = new Dictionary<string, decimal>();
foreach (var item in lvShareRateListSorted)
{
    string reasonName = item.EventReasonTitle;
    decimal percent = Convert.ToDecimal(item.TotalPercent);
    if (reasonPercentDict.ContainsKey(reasonName))
    {
        reasonPercentDict[reasonName] += percent;
    }
    else
    {
        reasonPercentDict.Add(reasonName, percent);
    }
}

// 如果后续仍需要两个独立列表,可从字典转换得到
List<string> reasonsName = reasonPercentDict.Keys.ToList();
List<object> reasonsPercent = reasonPercentDict.Values.Cast<object>().ToList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:15:03