Skip to content

Searching through Objects with multiple levels of Generic List Objects

Bryan Homrighous

Asked Aug 13, 2007, 1:55 PM EDT2 answers
Share
LinkedInX
 

Take a look at the following code.  You will notice that Cases contains a List<Bottles>.  Each Bottles Object contains a List<MyLabels>.  In my code I am handed a List<Cases>.  Now I need boil down the List<Cases> in to a List<MyLabels> I received!

 

How do I do this? 

 

Public List<MyLabels> getListOfLabels(List<Cases> cases)

{

\\A bunch of foreach(s)?

 

C#
}



public class MyLabels
{
private string brand;
public string Brand
{
get { return brand; }
set { brand = value; }
}
private int number;
public int Number
{
get { return number; }
set { number = value; }
}
public MyLabels(string Brand, int Number)
{
this.brand = Brand;
this.number = Number;
}
}

public class Bottles
{
private List<MyLabels> listoflabels = new List<MyLabels>();
public List<MyLabels> ListOfLabels
{
get { return listoflabels; }
set { listoflabels = value; }
}

public Bottles(List<MyLabels> ListOfLabels)
{
this.listoflabels = ListOfLabels;
}
}

public class Cases
{
private List<Bottles> bottlesincase = new List<Bottles>();
public List<Bottles> BottlesInCase
{
get { return bottlesincase; }
set { bottlesincase = value; }
}

public Cases(List<Bottles> BottlesInCase)
{
this.bottlesincase = BottlesInCase;
}
}

 

Thanks

 

Bryan

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Mike Gold
    0

    Although I suspect this problem would be easier to solve using the new LINQ technology, currently I suspect you do need a bunch of foreach's to get the list of labels from the list of bottles.  If you want a better way to index these items, you may consider using Dictionary's instead.  Then you could for example, use a bottle name to reference a list of labels. 

    The best way to figure out what set of structures you need though, is to understand what you are trying to do.

    I suspect a better approach to this problem is to have each class contain the list of things you want.  For example,  a bottle probably only has a single label, so you only need a Label field in your Bottle class and this would eliminate the label collection.   A case class would contain a list of bottles. (If all bottles are the same in the case, then this might not be necessary, you would only need a single bottle field and a count of the number of bottles in the case).

    Best,

    0
  • 0
    Thanks Mike,  I will foreach through the different levels.
    0