【问题标题】:Iterate(foreach) through member variable in C# in an array [duplicate]通过数组中的C#中的成员变量迭代(foreach)[重复]
【发布时间】:2021-05-20 11:55:56
【问题描述】:

是否可以不使用 temp 直接访问 foreach 标头中的变量 i?

class A
{
    public int i{get; set;}
}
...
A[] many_As=new A[1000]

foreach (var element in many_As)
{
    int temp=element.i;
    ...
}
...

->

foreach (int element in many_As.i)
{
   //doing something with element
   ...
}

【问题讨论】:

    标签: c# arrays linq for-loop


    【解决方案1】:

    你可以使用System.Linq:

    ...
    
    using System.Linq;
    
    ...
    
    
    foreach(var element in many_As.Select(x = >x.i)) 
    {
        //do something
    }
    

    【讨论】:

      【解决方案2】:

      从 C# 7 开始,您可以执行以下操作:

      foreach (var (value, index) in collection.Select((val, idx)=>(val, idx))) {
          Console.WriteLine($"{index + 1}th item is: {value}");
      }
      

      这里我们使用ValueTupletuple deconstruction

      【讨论】:

        猜你喜欢
        • 2016-10-24
        • 2011-05-26
        • 1970-01-01
        • 2022-01-15
        • 2010-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多