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(); } } }
Leave a Reply