C# 中List相关使用方法整理

1、取出classList中不包含rightClassList中成员,生成新的missingClassList

        private List<FireInfo> classList= new List<FireInfo>();
        private List<FireInfo> rightClassList = new List<FireInfo>();
        private List<FireInfo> missingClassList = new List<FireInfo>();   

        
    //取出缺少的--
   missingClassList = classList.Where(x => !rightClassList.Any(a => x.name == a.name)).ToList();

2、修改List中指定元素的值

  List<PointData> points = rightPoints.Where(x => x.pointTrs.name.Equals(args.transform.name)).ToList();
  points.ForEach((p) =>
  {
      p.pointTime = (int)phaseTime;
      p.pointTrs = args.transform;
      CommonFunc.SetTrs(p.selectIcon, true);
      if (p.selectIcon2)
          CommonFunc.SetTrs(p.selectIcon2, true);
      //截图
      OperationPhoto.Instance.GetOperationPhoto((Texture2D texture2D, string photoStr) =>
      {
          p.photo = UIManager_01.Instance.ShowPhotos(texture2D);
      });
  });

3、List 中Select、Any、Where、GroupBy的应用

    public void CarRunStatisticsInfoRefresh(CarRunStatisticsInfo[] carRunStatisticsInfos)
    {
        // foreach (var carRunStatisticsInfo in carRunStatisticsInfos)
        {

            IEnumerable<Vector2> thisMonthList = carRunStatisticsInfos.Select(e => new Vector2(e.timeVariable, (float)e.taskTimeCountThis));
            IEnumerable<Vector2> lastMonthList = carRunStatisticsInfos.Select(e => new Vector2(e.timeVariable, (float)e.taskTimeCountLast));
            List<Vector2> vector2ThisMonthList = new List<Vector2>();
            List<Vector2> vector2LastMonthList = new List<Vector2>();
            carRunStatisticsSeries_ThisMonth.theGraph.xAxis.AxisMinValue = 1;
            carRunStatisticsSeries_ThisMonth.theGraph.xAxis.AxisMaxValue = dateList.daysInMonth;
            carRunStatisticsSeries_ThisMonth.theGraph.xAxis.AxisNumTicks = (int)dateList.daysInMonth + 1;

            if (carRunStatisticsInfos.Select(e => e.taskTimeCountThis).Max() >= carRunStatisticsInfos.Select(e => e.taskTimeCountLast).Max())
            {
                if (carRunStatisticsInfos.Select(e => e.taskTimeCountThis).Max() > 0)
                {
                    carRunStatisticsSeries_ThisMonth.theGraph.yAxis.AxisMaxValue = (float)carRunStatisticsInfos.Select(e => e.taskTimeCountThis).Max();
                }

                // Debug.LogError("本月" + carRunStatisticsInfos.Select(e => e.taskTimeCountThis).Max() * 1.2f);
            }
            else
            {
                carRunStatisticsSeries_LastMonth.theGraph.yAxis.AxisMaxValue = (float)carRunStatisticsInfos.Select(e => e.taskTimeCountLast).Max();
                // Debug.LogError("上月" + carRunStatisticsInfos.Select(e => e.taskTimeCountThis).Max() * 1.2f);
            }

            for (int i = 1; i <= (int)dateList.daysInMonth; i++)
            {
                if (thisMonthList.Any(e => e.x == i))
                {
                    var v = thisMonthList.Where(e => e.x == i).First();
                    vector2ThisMonthList.Add(v);
                }
                else
                {
                    vector2ThisMonthList.Add(new Vector2(i, 0));
                }
                if (lastMonthList.Any(e => e.x == i))
                {
                    var v = lastMonthList.Where(e => e.x == i).First();
                    vector2LastMonthList.Add(v);
                }
                else
                {
                    vector2LastMonthList.Add(new Vector2(i, 0));
                }
            }

            carRunStatisticsSeries_ThisMonth.pointValues.SetList(vector2ThisMonthList);
            carRunStatisticsSeries_LastMonth.pointValues.SetList(vector2LastMonthList);
            IEnumerable<Vector2> thisYearList = carRunStatisticsInfos.Select(e => new Vector2(e.timeVariable, (float)e.taskTimeCountThis));
            IEnumerable<Vector2> lastYearList = carRunStatisticsInfos.Select(e => new Vector2(e.timeVariable, (float)e.taskTimeCountLast));
            List<Vector2> vectorsThisYearList = new List<Vector2>();
            List<Vector2> vectorsLastYearList = new List<Vector2>();
            if (carRunStatisticsInfos.Select(e => e.taskTimeCountThis).Max() >= carRunStatisticsInfos.Select(e => e.taskTimeCountLast).Max())
            {
                if (carRunStatisticsInfos.Select(e => e.taskTimeCountThis).Max() > 0)
                {
                    carRunStatisticsSeries_ThisYear.theGraph.yAxis.AxisMaxValue =
                        (float)carRunStatisticsInfos.Select(e => e.taskTimeCountThis).Max();
                }
            }
            else
            {
                carRunStatisticsSeries_LastYear.theGraph.yAxis.AxisMaxValue = (float)carRunStatisticsInfos.Select(e => e.taskTimeCountLast).Max();
            }

            for (int i = 1; i <= 12; i++)
            {
                if (thisYearList.Any(e => e.x == i))
                {
                    var v = thisYearList.Where(e => e.x == i).First();
                    vectorsThisYearList.Add(v);
                }
                else
                {
                    vectorsThisYearList.Add(new Vector2(i, 0));

                }
                if (lastYearList.Any(e => e.x == i))
                {
                    var v = lastYearList.Where(e => e.x == i).First();
                    vectorsLastYearList.Add(v);

                }
                else
                {
                    vectorsLastYearList.Add(new Vector2(i, 0));

                }
            }

            carRunStatisticsSeries_ThisYear.pointValues.SetList(vectorsThisYearList);
            carRunStatisticsSeries_LastYear.pointValues.SetList(vectorsLastYearList);
        }
    }

   

 public void ProductionLineInfoRefresh(ProductionLineInfo[] productionLineInfos)
    {
        if (productionLineInfos.Length > 0)
        {
            IEnumerable<IGrouping<string, ProductionLineInfo>> lineInfos =
                productionLineInfos.GroupBy(e => e.productionLineName);
            foreach (IGrouping<string, ProductionLineInfo> productionLine in lineInfos)
            {
                if (productionLine.Key == "生产线一")
                {
                    line1TotalProductiveCapacity = 0;
                    foreach (var info in productionLine)
                    {

                        line1TotalProductiveCapacity += (float)info.productionCapacity;
                    }
                    Debug.LogError("生产线一生产能力总和:" + line1TotalProductiveCapacity);

                    productivityLine1Series.theGraph.xAxis.AxisMinValue = 1;
                    productivityLine1Series.theGraph.xAxis.AxisMaxValue = dateList.daysInMonth;
                    productivityLine1Series.theGraph.xAxis.AxisNumTicks = (int)dateList.daysInMonth + 1;

                    if (productionLine.Select(e => e.productionCapacity).Max() > 0)
                    {
                        //if (productionLine.Select(e => e.productionCapacity).Max().ToString().Length > 5)
                        //{
                        //    productivityLine1Series.yAxis.AxisTitleString = "单位:吨";
                        //    productivityLine1Series.theGraph.yAxis.AxisMaxValue =
                        //        (float)productionLine.Select(e => e.productionCapacity).Max() / 1000 * 1.5f;

                        //    //将获取生产线一某月每日的数据存储
                        //    IEnumerable<Vector2> lineOneThisMonth = productionLine.Select(e =>
                        //        new Vector2(e.timeVariable, (float)e.productionCapacity / 1000f));
                        //    //定义存储生产线一某月每日数据
                        //    List<Vector2> lineOneThisMonthVector2 = new List<Vector2>();
                        //    //添加某月中每天的数据并存储
                        //    for (int i = 1; i <= (int)dateList.daysInMonth; i++)
                        //    {
                        //        if (lineOneThisMonth.Any(e => e.x == i))
                        //        {
                        //            var v = lineOneThisMonth.Where(e => e.x == i).First();
                        //            lineOneThisMonthVector2.Add(v);
                        //        }
                        //        else
                        //        {
                        //            lineOneThisMonthVector2.Add(new Vector2(i, 0));
                        //        }
                        //    }

                        //    //添加生产线一柱状图数据
                        //    productivityLine1Series.pointValues.SetList(lineOneThisMonthVector2);
                        //}
                        //else
                        {
                            productivityLine1Series.yAxis.AxisTitleString = "单位:千克";
                            productivityLine1Series.theGraph.yAxis.AxisMaxValue =
                                (float)productionLine.Select(e => e.productionCapacity).Max();
                            IEnumerable<Vector2> lineOneThisMonth = productionLine.Select(e =>
                                    new Vector2(e.timeVariable, (float)e.productionCapacity));
                            List<Vector2> lineOneThisMonthVector2 = new List<Vector2>();

                            for (int i = 1; i <= (int)dateList.daysInMonth; i++)
                            {
                                if (lineOneThisMonth.Any(e => e.x == i))
                                {
                                    var v = lineOneThisMonth.Where(e => e.x == i).First();
                                    lineOneThisMonthVector2.Add(v);
                                }
                                else
                                {
                                    lineOneThisMonthVector2.Add(new Vector2(i, 0));
                                }
                            }

                            productivityLine1Series.pointValues.SetList(lineOneThisMonthVector2);
                        }
                    }
                }
                else if (productionLine.Key == "生产线二")
                {

                    line2TotalProductiveCapacity = 0;
                    foreach (var info in productionLine)
                    {
                        line2TotalProductiveCapacity += (float)info.productionCapacity;

                    }
                    Debug.LogError("生产线二生产能力总和:" + line2TotalProductiveCapacity);

                    productivityLine2Series.theGraph.xAxis.AxisMinValue = 1;
                    productivityLine2Series.theGraph.xAxis.AxisMaxValue = dateList.daysInMonth;
                    productivityLine2Series.theGraph.xAxis.AxisNumTicks = (int)dateList.daysInMonth + 1;

                    if (productionLine.Select(e => e.productionCapacity).Max() > 0)
                    {
                        //if (productionLine.Select(e => e.productionCapacity).Max().ToString().Length > 5)
                        //{
                        //    productivityLine2Series.theGraph.yAxis.AxisMinValue =
                        //        (float)productionLine.Select(e => e.productionCapacity).Max() / 1000 * 1.5f;
                        //    //将获取生产线二今年每月的数据存储
                        //    IEnumerable<Vector2> line2ThisYear = productionLine.Select(e =>
                        //        new Vector2(e.timeVariable, (float)e.productionCapacity / 1000f));
                        //    //定义存储生产线二今年每月数据
                        //    List<Vector2> line2ThisYearVector2 = new List<Vector2>();
                        //    //添加一年中每月的数据
                        //    for (int i = 1; i <= (int)dateList.daysInMonth; i++)
                        //    {
                        //        if (line2ThisYear.Any(e => e.x == i))
                        //        {
                        //            var v = line2ThisYear.Where(e => e.x == i).First();
                        //            line2ThisYearVector2.Add(v);
                        //        }
                        //        else
                        //        {
                        //            line2ThisYearVector2.Add(new Vector2(i, 0));
                        //        }
                        //    }

                        //    //添加生产线二柱状图数据
                        //    productivityLine2Series.pointValues.SetList(line2ThisYearVector2);
                        //}
                        //else
                        {
                            productivityLine2Series.theGraph.yAxis.AxisMinValue =
                                (float)productionLine.Select(e => e.productionCapacity).Max();
                            IEnumerable<Vector2> line2ThisYear = productionLine.Select(e =>
                                  new Vector2(e.timeVariable, (float)e.productionCapacity));
                            List<Vector2> line2ThisYearVector2 = new List<Vector2>();
                            for (int i = 1; i <= (int)dateList.daysInMonth; i++)
                            {
                                if (line2ThisYear.Any(e => e.x == i))
                                {
                                    var v = line2ThisYear.Where(e => e.x == i).First();
                                    line2ThisYearVector2.Add(v);
                                }
                                else
                                {
                                    line2ThisYearVector2.Add(new Vector2(i, 0));
                                }
                            }

                            productivityLine2Series.pointValues.SetList(line2ThisYearVector2);
                        }
                    }

                }

            }

            Debug.LogError("生产能力总和:" + line1TotalProductiveCapacity);
            //if (line1TotalProductiveCapacity.ToString().Length > 8)
            //{
            //    totalProductionLine1Unit.text = "吨";
            //    totalProductionLine1.text = (line1TotalProductiveCapacity / 1000f).ToString("0.00");
            //}
            //else
            {
                totalProductionLine1Unit.text = "千克";
                totalProductionLine1.text = line1TotalProductiveCapacity.ToString("0.00");
            }

            //if (line2TotalProductiveCapacity.ToString().Length > 8)
            //{
            //    totalProductionLine2Unit.text = "吨";
            //    totalProductionLine2.text = (line2TotalProductiveCapacity / 1000f).ToString("0.00");
            //}
            //else
            {
                totalProductionLine2Unit.text = "千克";
                totalProductionLine2.text = line2TotalProductiveCapacity.ToString("0.00");
            }

            //if ((line1TotalProductiveCapacity / dateList.daysInMonth).ToString().Length > 6)
            //{
            //    averageProductivityLine1Unit.text = "吨/天";
            //    averageProductivityLine1.text = ((line1TotalProductiveCapacity / dateList.daysInMonth) / 1000f).ToString("0.00");

            //}
            //else
            {
                averageProductivityLine1Unit.text = "千克/天";
                averageProductivityLine1.text = (line1TotalProductiveCapacity / dateList.daysInMonth).ToString("0.00");
            }

            //if ((line2TotalProductiveCapacity / dateList.daysInMonth).ToString().Length > 6)
            //{
            //    averageProductivityLine2Unit.text = "吨/天";
            //    averageProductivityLine2.text = ((line2TotalProductiveCapacity / dateList.daysInMonth) / 1000).ToString("0.00");

            //}
            //else
            {
                averageProductivityLine2Unit.text = "千克/天";
                averageProductivityLine2.text = (line2TotalProductiveCapacity / dateList.daysInMonth).ToString("0.00");
            }
            ErrorToolTip.Instance.DestroyTooltip();
        }
        else
        {

            List<Vector2> lineOneThisMonthVector2 = new List<Vector2>();

            for (int i = 1; i <= (int)dateList.daysInMonth; i++)
            {
                lineOneThisMonthVector2.Add(new Vector2(i, 0));
            }

            productivityLine1Series.pointValues.SetList(lineOneThisMonthVector2);
            productivityLine2Series.pointValues.SetList(lineOneThisMonthVector2);
            totalProductionLine1.text = "0";
            totalProductionLine2.text = "0";
            averageProductivityLine1.text = "0";
            averageProductivityLine2.text = "0";

            ErrorToolTip.Instance.DestroyTooltip();
        }


    }

4.List 中Select、Exists、Where的应用

  var tempList = rightPoints.Select(r => r.photo).ToList();
  bool isExist = tempList.Exists(t => t == parent);
  Debug.LogFormat("<color=yellow>{0}是否存在:{1}</color>", parent, isExist);
  if (isExist)
  {
      rightCount--;
      List<PointData> pointDatas = rightPoints.Where(x => x.photo == parent).ToList();
      pointDatas.ForEach(p =>
      {
          p.pointTime = 0;
          CommonFunc.SetCollider(p.pointTrs, true);
          CommonFunc.SetTrs(p.selectIcon, false);
          GameObject.Destroy(p.photo);
          p.photo = null;
      });
  }
  else {
      errorCount--;
      errorPoints.Where((val) => val.photo.name == parent.name).ToList().ForEach(e =>
      {
          CommonFunc.SetCollider(e.pointTrs, true);
          CommonFunc.SetTrs(e.selectIcon, false);
          GameObject.Destroy(e.photo);
      });
      //移除指定元素
      errorPoints = errorPoints.Where((val) => val.photo.name != parent.name).ToList();
  }

<think>嗯,用户想了解C#中foreach的使用方法,包括教程、示例和语法。首先,我需要根据用户提供的引用资料整理出清晰的回答结构。用户给的引用1到4都提到了foreach的基本语法、遍历数组、集合以及字典的例子,还有注意事项。 首先,我应该从语法开始,引用1提到foreach循环用于遍历实现了IEnumerable接口的对象,语法结构是foreach (元素类型 变量 in 集合)。然后,给出遍历数组的示例,比如引用2中的代码,展示int数组的遍历。接着是集合,比如引用3中的List<int>例子,说明同样的语法适用于不同的集合类型。 接下来是字典的遍历,引用4提到使用KeyValuePair来访问键和值,需要展示如何遍历字典的键值对。然后,可能还要提到其他集合类型,比如字符串中的字符,或者自定义集合,这样用户知道foreach的广泛应用。 然后,注意事项部分,比如不能修改集合元素,只能读取。引用1和引用3都提到foreach简化了遍历,无需管理索引,但修改元素会导致异常。这里需要提醒用户注意。 接下来是常见错误,比如尝试在循环中修改集合,或者使用错误的变量类型,比如遍历字典时没有用KeyValuePair。引用4中的字典例子正好可以说明正确用法。 最后,生成相关问题,可能涉及性能、与for循环的比较、自定义集合的支持等。这些需要结合用户可能遇到的进一步疑问来设计。 整理结构的时候要确保每个部分都有对应的引用标注,比如语法部分用引用1,数组示例用引用2,集合示例用引用3,字典用引用4。同时,代码示例要正确,符合C#语法,并且用代码块格式展示。 还需要检查是否有遗漏的信息,比如foreach只能用于IEnumerable对象,这点在引用1中提到,需要在语法部分说明。另外,注意事项里是否还有其他点,比如迭代过程中集合被修改会抛出异常,这也需要提及。 可能用户是初学者,所以语言要尽量通俗,步骤清晰,示例明确。避免使用过于专业的术语,或者在必要时解释清楚。比如解释KeyValuePair是什么,为什么在遍历字典时需要用到它。 最后,确保回答符合用户的要求,结构包括语法、示例、注意事项、常见错误,并且相关问题能够引导用户进一步学习。可能需要检查每个引用是否正确对应到内容,避免混淆。比如引用3中的List示例是否正确,引用4的字典是否正确处理键值对。 总结下来,回答的结构应该是: 1. 基本语法(引用1) 2. 示例部分: a. 遍历数组(引用2) b. 遍历集合如List(引用3) c. 遍历字典(引用4) 3. 其他集合类型 4. 注意事项(不可修改元素,引用1、3) 5. 常见错误(修改元素,变量类型错误) 6. 相关问题 现在把这些部分组织起来,确保每个部分都有对应的引用,并且示例代码正确无误。同时,使用中文回答,行内公式用$...$,但在这个问题中可能不太需要数学公式,但如果有的话要符合格式。独立公式如果有的话要用$$...$$,但这里可能不需要。 检查是否有遗漏的信息,比如foreach在遍历字符串时的应用,或者如何实现自定义集合支持foreach,这些可能也是用户感兴趣的点,可以放在其他集合类型部分。 最后,确保生成的相关问题有针对性,比如性能优化、异常处理、与其他循环结构的对比等,帮助用户深入理解。</think>### C# foreach 循环使用详解 #### 一、基本语法 `foreach` 循环用于遍历实现了 `IEnumerable` 或 `IEnumerable<T>` 接口的集合(如数组、列表、字典等)。其语法结构为: ```csharp foreach (元素类型 变量 in 集合) { // 操作代码 } ``` 例如:`foreach (int num in numbers)` 表示遍历整数集合中的每个元素[^1]。 --- #### 二、示例演示 1. **遍历数组** ```csharp int[] numbers = { 1, 2, 3, 4, 5 }; foreach (int num in numbers) { Console.WriteLine(num); } ``` 输出结果依次为 1 到 5[^2]。 2. **遍历列表** ```csharp List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" }; foreach (string fruit in fruits) { Console.WriteLine(fruit); } ``` 输出结果为列表中每个水果名称[^3]。 3. **遍历字典** ```csharp Dictionary<int, string> students = new Dictionary<int, string> { { 101, "Alice" }, { 102, "Bob" } }; foreach (KeyValuePair<int, string> entry in students) { Console.WriteLine($"ID: {entry.Key}, Name: {entry.Value}"); } ``` 输出结果为字典中的键值对[^4]。 --- #### 三、其他集合类型 - **字符串遍历字符** ```csharp string text = "Hello"; foreach (char c in text) { Console.WriteLine(c); // 输出 H, e, l, l, o } ``` - **自定义集合** 若类实现了 `IEnumerable` 接口,也可通过 `foreach` 遍历。 --- #### 四、注意事项 1. **只读访问** 在 `foreach` 循环中无法直接修改集合元素。例如以下代码会报错: ```csharp foreach (int num in numbers) { num = num * 2; // ❌ 编译错误:无法修改迭代变量 } ``` 2. **迭代中集合不可变** 遍历时若对集合进行增删操作(如 `Add()` 或 `Remove()`),会抛出 `InvalidOperationException`。 3. **类型匹配** 变量类型需与集合元素类型一致。例如遍历字典时必须使用 `KeyValuePair<TKey, TValue>`。 --- #### 五、常见错误场景 ```csharp // 错误1:尝试修改集合 List<int> list = new List<int> { 1, 2, 3 }; foreach (int item in list) { list.Add(4); // ❌ 运行时异常:集合已更改 } // 错误2:变量类型不匹配 Dictionary<int, string> dict = new Dictionary<int, string>(); foreach (int key in dict) // ❌ 应使用 KeyValuePair<int, string> { // ... } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值