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

Published on December 30, 2013 by Senthil Kumar

Filed under C#

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star

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);
}

}
}```

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);
}

}
}```

﻿
x

You might be Interested in these Posts

C Program to convert lower case string to upper case

Problem Statement Write a program in C to convert the given string from lower case to upper case. ...

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...