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

C#中如何提取数组中小于5的元素并存入新数组?

问题分析与解决方案

你的代码存在两个核心问题:

  1. C#中普通int[]是固定长度数组,初始化int[] b = { };后数组长度永久为0,Append方法不会修改原数组(它返回新的IEnumerable<int>但你未接收),因此无法添加元素。
  2. 缺少打印结果的代码逻辑。

以下是三种可行的实现方式:


方案1:用List(常规简便写法)

List<int>是动态长度集合,适合动态添加元素,最后可转为固定数组:

using System;
using System.Collections.Generic;

namespace exercices
{
    class Hello
    {
        static void Main(string[] args)
        {
            int[] a = { 1, 2, 3, 4, 5, 6 };
            List<int> bList = new List<int>();

            foreach (int num in a)
            {
                if (num < 5)
                {
                    bList.Add(num);
                }
            }

            int[] b = bList.ToArray();
            Console.WriteLine(string.Join(", ", b)); // 打印结果:1, 2, 3, 4
        }
    }
}

方案2:用LINQ一行实现(极简写法)

借助LINQ的筛选方法直接完成逻辑,需引入System.Linq命名空间:

using System;
using System.Linq;

namespace exercices
{
    class Hello
    {
        static void Main(string[] args)
        {
            int[] a = { 1, 2, 3, 4, 5, 6 };
            int[] b = a.Where(num => num < 5).ToArray();

            Console.WriteLine(string.Join(", ", b));
        }
    }
}

方案3:纯数组手动实现(无集合/依赖)

先统计符合条件的元素数量,再创建对应长度的数组填充:

using System;

namespace exercices
{
    class Hello
    {
        static void Main(string[] args)
        {
            int[] a = { 1, 2, 3, 4, 5, 6 };
            int count = 0;

            // 第一步:统计符合条件的元素数
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] < 5) count++;
            }

            // 第二步:创建对应长度的数组并填充
            int[] b = new int[count];
            int index = 0;
            for (int i = 0; i < a.Length; i++)
            {
                if (a[i] < 5)
                {
                    b[index] = a[i];
                    index++;
                }
            }

            Console.WriteLine(string.Join(", ", b));
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:10:28