Rewrite - Hat Operator with foreach - C#

Shervan360 1,661 Reputation points
2022-06-08T17:46:49.507+00:00

Hello,

How can I rewrite the snippet code with foreach?

static void Main(string[] args)  
        {  
            IEnumerable<int> myInt = Enumerable.Range(10, 11);  
            int[] myArr = myInt.ToArray();  
            for (int i = 1; i <= myArr.Length; i++)  // rerwite this with foreach loop  
            {  
                Console.Write($"{myArr[^i],-5}");  
            }  
            Console.WriteLine();  
        }  
Developer technologies | C#
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-06-08T19:08:36.867+00:00

    You do realize ^ is from the end. Seems like it makes sense to go from start to end e.g.

    private static void ForEachIndexingForumQuestion()  
    {  
        var intList = Enumerable.Range(10, 11).ToList();  
        Range range = new Range(1, intList.Count);  
        foreach (var index in range)  
        {  
            Console.WriteLine($"{index, -3}{intList[index]}");  
        }  
      
        Console.ReadLine();  
      
    }  
    private static void ForEachIndexingForumQuestion2()  
    {  
        var intList = Enumerable.Range(10, 11).ToList();  
      
        foreach (var index in 1..intList.Count)  
        {  
            Console.WriteLine($"{index,-3}{intList[index]}");  
        }  
      
        Console.ReadLine();  
      
    }  
    

    Another perspective (reverse)

    private static void ForEachIndexingForumQuestion3()  
    {  
          
        var intList = Enumerable.Range(10, 11).ToList();  
        for (int index = intList.Count; index != 0; index--)  
        {  
            var currentIndex = new Index(index, true);  
            Console.WriteLine($"{currentIndex,-5}{intList[currentIndex]}");  
        }  
      
        Console.WriteLine();  
      
        var reversed = Enumerable.Range(10, 11).Reverse().ToList();  
        foreach (var index in ..reversed.Count)  
        {  
            Console.WriteLine($"{index,-5}{reversed[index]}");  
        }  
      
        Console.ReadLine();  
    }  
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.