Calculate top 4 values

  • Thread starter Thread starter Robert Bravery
  • Start date Start date
R

Robert Bravery

Hi all,

C# How could I sum, the top 4 values of a bunch of values

THanks
RObert
 
Robert Bravery said:
C# How could I sum, the top 4 values of a bunch of values

How is this "bunch" represented?
How efficient does it have to be?
What version of C# and .NET are you using?
 
If you are using .NET 3.5, how about:

var sum = data.Take(4).Sum();

Otherwise just loop with an escape:

int count = 0, sum = 0;
foreach (int value in data)
{
count++;
if (count > 4) break;
sum += value;
}

If the data is an array/list you could also use the indexer approach, but
you need to worry about 2 end points (the end of the array, and the end of
the desired TOP)...

Marc
 
I'd add to that:
by "top" do you mean "largest" or "first" (the latter being the SQL meaning
of "top")
(since 2 posts already show the ambiguity)

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top