-9

I'm not an expert in programming and like to challenge myself sometimes when I'm free at work, so as the title says, just using a simple for-loop to get the max value of a column without the use of "Max(...)", is that possible?

EDIT: Here's an example

string getMax()
{
    SqlCommand com = new SqlCommand("Select Max(UnitPrice) From Products", con);
    con.Open();
    string mx = com.ExecuteScalar().ToString();
    con.Close();
    return mx;
}

I meant Max in the SQLCommand, sorry for the confusion.

Meshal
  • 3
  • 2
  • 3
  • Why use a loop? Just sort by the column desc and take the first element – juergen d Mar 06 '16 at 23:41
  • @juergend every sort algorithm has to go through all elements the one or other way just like a loop does. So aside from the edge case where the input is alredy sorted a loop will always perform much better. – Bill Tür stands with Ukraine Mar 07 '16 at 07:20
  • @ThomasSchremser: No. A loop is exactly the same because it has to go through all elements too. And a DB will sort most likely faster that you can go to a loop. BTW sorting before going to a loop pushes performance a lot. See http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array – juergen d Mar 07 '16 at 09:15
  • @juergend: At the time I commented there was no mention of a DB (where the performance of an `ORDER BY` heavily depends on the query, indexes,...). You certainly are right that there are cases where soritng before looping can improve performance (as your link shows) but I very much doubt that this would be the case in a simple search for a max value as the OP asked for. – Bill Tür stands with Ukraine Mar 07 '16 at 11:13
  • @juergend: I just realized the `sql-server` tag; I came to the question via the `c#` tag – Bill Tür stands with Ukraine Mar 07 '16 at 11:16

2 Answers2

4

just using a simple for-loop to get the max value of a column without the use of "Max(...)", is that possible?

Well, the people who implemented Max did not have Max at their disposal because it hadn't been written yet. They wrote it. So the answer to your question is "yes, that is possible".

If you want to know how they did it, read the source code for Max and then you'll know.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • 2
    Damn it Eric, you beat me by 20 seconds :-) You might want to include the [link](http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,6ca1a80e1f22e519) though. – Gediminas Masaitis Mar 06 '16 at 23:58
3

It's definitely possible. Think about how Max() might work behind the scenes. Think about how you might determine if one number is greater than another number, then apply that logic in the for loop, keeping track each time of the biggest number.

David Klempfner
  • 8,700
  • 20
  • 73
  • 153