MVC loop through array to find data of each location in a table and create a seperate table for each

58 views Asked by At

I want to be able to loop though my "Sites" sql table in order to find all the costs of items in the table if items are not null of each "site" location

Here is my current controller method

float[] osiItemCost;
float[] osiLoItemCost;
float[] osiItemLastCost;

List<Site> sites = db.Sites.ToList();
            foreach (Site s in sites)
            {
                foreach (OffSiteItemDetails d in s.ItemDetails)
                {

                    if (d.itemID != null)
                    {
                        osiItemCost[s.ID] = d.qty * db.Items.Where(x => x.ID == d.itemID).FirstOrDefault().cost(1, false, false);
                        osiLoItemCost[s.ID] += d.qty * db.Items.Where(x => x.ID == d.itemID).FirstOrDefault().cost(1, false, true);
                        osiItemLastCost[s.ID] += db.Items.Where(x => x.ID == d.itemID).FirstOrDefault().cost(d.qty, true, false);

                    }
                 }
             }

I want it to loop through and grab the data for each site then assign it to its respective variable site location. for example: osiItemCost[s.ID] But I don't know if I am on the right track.

The purpose and ultimate goal of this is that I want to then create a table for each "site" that will show their appropriate data. This was a difficult question to word so if you need more clarity just let me know

1

There are 1 answers

0
Michael G On BEST ANSWER

Try creating a model that represents the data you want in the table, something like:

public class AppropriateSiteData{
    public int Id {get;set;}
    public int SiteId {get;set;}
    public float ItemCost {get;set}
    public float LoItemCost {get;set;}
    public float ItemCostLast {get;set;}    
}

and then create a List of the model, and add to the list when looping over your data:

List<AppropriateSiteData> siteDataList = new List<AppropriateSiteData>();
List<Site> sites = db.Sites.ToList();

        foreach (Site s in sites)
        {
            foreach (OffSiteItemDetails d in s.ItemDetails)
            {

                if (d.itemID != null)
                {
                   AppropriateSiteData toAdd = new AppropriateSiteData{
                           SiteId = s.Id,
                           ItemCost = d.qty * db.Items.Where(x => x.ID == 
                                      d.itemID).FirstOrDefault().cost(1, false, false),
                           LoItemCost = d.qty * db.Items.Where(x => x.ID == 
                                       d.itemID).FirstOrDefault().cost(1, false, true),
                           ItemCostLast =db.Items.Where(x => x.ID == 
                           d.itemID).FirstOrDefault().cost(d.qty, true, false)
                      };
                   siteDataList.Add(toAdd); 

                }
             }
         }

Then siteDataList will contain a list of the data you're looking for.