Consider I have an array like the following one:
string[] Files = {"NO. 1", "NO. 2", "NO. 3", "NO. 4", "NO. 5", "NO. 6", "NO. 7"};
I want to find the element with the maximum number. How can I do this by Linq queries in C#?
If you are using LINQ to objects (rather than to a database)... then this'll do it.
string[] Files = { "NO. 1", "NO. 2", "NO. 3", "NO. 4", "NO. 5", "NO. 6", "NO. 7" };
var max = Files.OrderByDescending(x => int.Parse(x.Replace("NO. ", ""))).First();
The exact string manipulation will of course change if your list is some way different to what you posted.
There may be more elegant LINQ functions you can use, but these are the ones I found.
var z = Files.Max(x => int.Parse(x.Replace("NO. ", "")));
which retrieves the max number, not the max element.
Jan 28, 2012 at 8:57
linq Select
,int.Parse
,linq Max
,string.indexOf
,string.Substring
:P