How to Get the Maximum value from a List of String using LINQ in C# ?

Published on December 30, 2013 by abundantcode

Filed under C#

Last modified December 30, 2013

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 0 (0 votes)

This article have been viewed 9045 times

In one of the previous article , we explained how to get the maximum value from a list of integer using LINQ query in C# . What happens when the column is a string instead of integer ?. Below are 2 possibilities on how to get the maximum value from a list of string.

How to Get the Maximum value from a List of String using LINQ in C# ?

If the logic to find the maximum value is based on the length of string in the column , below is the sample code do it.

The same logic as the previous one is applicable still . The use of the max function will do the trick.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
namespace AbundantCode
{
    internal class Program
    {

        private static void Main(string[] args)
        {

            string[] StockNos = new string[] { "ITM1179", "ITM235", "ITM9865", "ITM2365" };
            // Get Max using LINQ Query
            var result = (from m in StockNos
            select m).Max();
            Console.WriteLine(result);
            Console.ReadLine();
        }

    }
}

If the logic is based on the value to split the first 3 letters “ITM” and get the numeric value and perform the operation , below is the code snippet to do it.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
namespace AbundantCode
{
    internal class Program
    {

        private static void Main(string[] args)
        {

            string[] StockNos = new string[] { "ITM1179", "ITM235", "ITM9865", "ITM2365" };
            // Get Max using LINQ Query and string replace
            var result = (from m in StockNos

                          select m).OrderByDescending(a => int.Parse(a.Replace("ITM", ""))).FirstOrDefault(); ;
            Console.WriteLine(result);
            Console.ReadLine();
        }

    }
}

How to Get the Maximum value from a List of String using LINQ in C# ?

Leave a Comment


x

You might be Interested in these Posts

How to decode a base64 string in C#?

Here's a sample code snippet demonstrating how you can easily decode a base64 encoded string in C#. ...

How to disable editing of items in a combo box in c#?

When working in Win forms using C# and especially when you use the combo box , you would have notice...

C# Program to find the ASCII Value of a Character

Problem Write a program in Visual C# to find the ASCII value of the input character. How to find t...