0

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

3
  • Read about linq linq Select, int.Parse, linq Max, string.indexOf, string.Substring :P Commented Jan 28, 2012 at 8:46
  • What do you mean with maximum number? Do you want to parse the number from the "NO. X" string, where X is the required number and select the string with the highest X? Commented Jan 28, 2012 at 8:52
  • If the string "NO." is a constant (i.e. it never changes), then just use "var highest = Files.OrderByDescending(x => x).First()". Commented Nov 5, 2013 at 22:57

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The answer I originally posted was var z = Files.Max(x => int.Parse(x.Replace("NO. ", ""))); which retrieves the max number, not the max element.
You can replace Take(1).Single() by First().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.