How to find the shortest string in array of strings in C#

3 Answers

0 votes
using System;
using System.Linq;
 
class Program
{
    static void Main() {
        string[] arr = {"c++", "python", "c#", "java"};
         
        int shortest_size = arr.Min(s=>s.Length);
        string shortest_string = arr.FirstOrDefault(s=>s.Length == shortest_size);
 
        Console.Write(shortest_string);
    }
}
 
 
 
/*
run:
 
c#
 
*/

 



answered Mar 7, 2021 by avibootz
0 votes
using System;
using System.Linq;

class Program
{
    static void Main() {
        string[] arr = {"c++", "python", "c#", "java"};
        
        string shortest_string = arr.OrderBy(s => s.Length).FirstOrDefault();

        Console.Write(shortest_string);
    }
}



/*
run:

c#

*/

 



answered Mar 7, 2021 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        string[] arr = {"c++", "python", "c#", "java"};
         
        string shortest_string = arr[0];
        foreach (string s in arr) {
            if (s.Length < shortest_string.Length) {
                shortest_string = s;
            }
        }
        Console.Write(shortest_string);
    }
}
 
 
 
/*
run:
 
c#
 
*/

 



answered Mar 7, 2021 by avibootz
...