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

C#列表与字典互转时出现StackOverflowException异常求助

List与Dictionary互转实现及StackOverflowException解决

一、当前代码问题

你提供的Conversion类是空的,未实现ListToDictionary和DictionaryToList方法;你提到的StackOverflowException大概率是之前尝试实现时写了无限递归代码(比如方法内部重复调用自身且无终止条件)导致的。

二、正确实现互转方法

下面是完整的Conversion类实现,包含两种集合的互转逻辑:

class Conversion
{
    // 将List<string>转为Dictionary<int, string>,用元素索引作为Key
    public Dictionary<int, string> ListToDictionary(List<string> list)
    {
        // 基础循环实现
        var dict = new Dictionary<int, string>();
        for (int i = 0; i < list.Count; i++)
        {
            dict.Add(i, list[i]);
        }
        return dict;

        // 或者用LINQ简化写法(需保留using System.Linq;)
        // return list.Select((item, index) => new { Index = index, Item = item })
        //            .ToDictionary(x => x.Index, x => x.Item);
    }

    // 将Dictionary<int, string>转回List<string>,提取Value集合
    public List<string> DictionaryToList(Dictionary<int, string> dictionary)
    {
        // 直接提取Values并转为List
        return dictionary.Values.ToList();

        // 如果需要按Key排序后再转List,用下面的代码
        // return dictionary.OrderBy(kv => kv.Key).Select(kv => kv.Value).ToList();
    }
}

三、StackOverflowException的原因与避免

如果之前你写了类似下面的错误代码,就会触发无限递归,最终导致栈溢出:

// 错误示例:无限递归调用自身
public Dictionary<int, string> ListToDictionary(List<string> list)
{
    return ListToDictionary(list); // 无终止条件,无限循环调用
}

避免这类问题的核心是:确保方法内部没有无意义的自调用,所有递归逻辑必须有明确的终止条件。

四、运行说明

替换你的Conversion类后,代码运行时会先输出字典的键值对,再输出转回的列表内容,符合你原本的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:12:26