moorara
moorara

Reputation: 4226

How to get max element in a string array by linq?

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#?

Upvotes: 0

Views: 4772

Answers (1)

perfectionist
perfectionist

Reputation: 4346

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.

Upvotes: 5

Related Questions