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

C# LINQ Select有返回值但as转List后变量为null问题

LINQ Select返回结果但as转List后变量为null问题定位

相关实现代码

private static readonly List<long> KnownPrimes = new List<long>() { 2, 3, 5, 7};
        
static void Main(string[] args)
{
    int numDivisors;
    string input = "";
    bool first = true;
    while (!int.TryParse(input, out numDivisors))
    {
        if(!first) Console.WriteLine("You must enter a number with no other characters.");
        Console.WriteLine("Find the least common multiple for numbers 1 through:");
        input = Console.ReadLine();
        first = false;
    }

    int index = -1;
    // 确保素数列表长度足够
    while (index == -1)
    {
                
        index = KnownPrimes.FindIndex(n => n > numDivisors);
        if(index == -1) AppendNextPrime();
     }
     // 初始化全0计数列表
     List<int> countPrimes = KnownPrimes.Select(n=>0) as List<int>;

调试异常现象

在Rider中调试上述最后一行代码时,调试面板显示如下信息:

Enumerable.Select() returned: Count = 5       countPrimes: null

即LINQ的Select方法本身未返回null,调试结果显示方法返回了元素数量为5的结果,但countPrimes变量始终为null。

问题原因

  • Select()方法的返回值类型 不是List<int>:LINQ的Select是延迟执行的投影方法,返回的是框架内部定义的迭代器类型(命名类似SelectListIterator),仅实现了IEnumerable<int>接口,和List<int>不存在继承/实现关系。
  • 使用as运算符做类型转换时,如果源对象和目标类型不匹配,会直接返回null,不会抛出异常,这就是countPrimes为null的直接原因。
  • 调试器显示的Count = 5是调试器自动枚举Select返回的迭代器、遍历所有元素得到的计数,不代表返回的对象本身是List<int>类型。

修复方案

不要直接用as将Select返回值转为List<int>,需要显式调用ToList()方法将投影结果实体化为列表类型,修正后的代码如下:

List<int> countPrimes = KnownPrimes.Select(n=>0).ToList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 09:18:27