Question

Alright so I didn't really know how to word this question, but I did my best. The goal I am trying to accomplish is to go through categories using a foreach loop. Inside the category foreach loop another foreach loop will go through Numbers. Right now it is grabbing ever value in the tables and storing them into an array. My goal is to only store the highest number in each category into the array.

Here is how the tables would look:

Category Table  

Title        NumberId

Type            1
Priority        2
Likelihood      3

Numbers Table

Order        NumberId
  3              1
  2              1
  1              1
  3              2
  2              2
  1              2
  3              3
  2              3
  1              3

So my goal would be instead of storing every order value into the array. I would like to store the highest number according to each number id. So there array would include 3,3,3.

This is what I have that stores every number into an array:

int[] values = new int[count];

foreach(var x in Category)
{
   foreach(var w in x.Numbers)
   {
      values[y] = w.Order;
      y++;
   }
}

Solution:

int[] values = new int[count];

foreach(var x in Category)
{
   foreach(var w in x.Numbers)
   {
       values[y] = x.Numbers.Select(o => o.Order).Max();
       y++;
       break;
    }
}
Was it helpful?

Solution

You can use IEnumerable.Max() :

foreach(var x in Category)
{
    values[y] = x.Numbers.Select(o => o.Order).Max();
    y++;
}

OTHER TIPS

This can be accomplished relatively easily through LINQ as:

int[] values = new int[count];

foreach(var x in Category)
{
    values.[y] = x.Numbers.OrderBy(w => w.Order).Reverse().First();
    y++;
}

This orders the x.Numbers by their ascending order, reverses the order (to place the highest value first in the order), and then selects the first value.

Ensure with this method that you've actually got a value for x.Number, else you'll get an exception thrown by the .First() call.

If you're unable to use LINQ (e.g. if you're on .NET 2.0), then consider using a Dictionary with the Category as the key, and the highest Number as the value:

Dictionary<int, int> categoriesByHighestOrders = new Dictionary<int, int>();
foreach(var x in Category)
{
    if (!categoriesByHighestOrders.Keys.Contains[x.SomeIndetifier])
        categoriesByHighestOrders.Add(x.SomeIdentifier, 0);
   foreach(var w in x.Numbers)
   {
        if (categoriesByHighestOrders[x.SomeIndetifier] < w.Order
            categoriesByHighestOrders[x.SomeIndetifier] = w.Order;
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top