How to get the last value inside foreach loop in C#

3 Answers

0 votes
using System;
 
class Program
{
    static void Main() {
        string[] arr = { "c#", "c", "c++", "java", "rust" };
        int i = 0, size = arr.Length;
          
        foreach (string s in arr) {
            Console.WriteLine(i + " " + s);
            i++;
            if (i == size) {
                Console.WriteLine("Last = {0}", s);
            }
        }
    }
}
 

 
 
/*
run:
 
0 c#
1 c
2 c++
3 java
4 rust
Last = rust
 
*/

 

 



answered Aug 28, 2023 by avibootz
0 votes
using System;
using System.Collections.Generic;

class Program
{
    static void Main() {
        var lst = new List<int> { 55, 88, 33, 11, 100, 70 };
        int total = lst.Count, i = 0;

        foreach (int element in lst) {
            Console.WriteLine(i + " " + element);
            i++;
            if (i == total) {
                Console.WriteLine("Last = {0}", element);
            }
        }
    }
}
 
 
 
 
/*
run:
 
0 55
1 88
2 33
3 11
4 100
5 70
Last = 70
 
*/

 

 



answered Aug 28, 2023 by avibootz
0 votes
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    static void Main() {
        var lst = new List<int> { 55, 88, 33, 11, 100, 70 };
        int last = lst.Last();

        foreach (int element in lst) {
            Console.WriteLine(element);
            if (last == element) {
                Console.WriteLine("Last = {0}", element);
            }
        }
    }
}
 
 
 
 
/*
run:
 
55
88
33
11
100
70
Last = 70
 
*/

 

 



answered Aug 28, 2023 by avibootz

Related questions

1 answer 102 views
102 views asked Aug 8, 2024 by avibootz
1 answer 148 views
148 views asked Mar 6, 2023 by avibootz
2 answers 184 views
184 views asked Nov 25, 2020 by avibootz
1 answer 188 views
1 answer 189 views
2 answers 283 views
...