Split list in sublists based on OOP

74 Views Asked by At

In C#, given a list of objects

Is there a way to create sublists by the number of each object from that list of objects?

Example:

Input:

Main list:

Object A= {"Erick", "Cartman", 3}
Object B= {"Angelina", "Jollie", 4}
Object C= {"Anton", "Azul", 4}
Object D= {"Random", "Data", 5}

Output:

Sublist 1:

Object A= {"Erick", "Cartman", 3}

Sublist 2:

Object B= {"Angelina", "Jollie", 4}   // this sublist will only have number 4 objects
Object C= {"Anton", "Azul", 4}

Sublist 3:

Object D= {"Random", "Data", 5}

Consider that the main list may contain more than 1000 objects, therefore, theres no way to tell how many sublists are going to pop out

1

There are 1 best solutions below

1
Justin Kirk On
List<List<Object>> list = new List<List<Object>>();
int currentnumber; 
List<Object> currentList = new List<Object>();   
foreach(object a in objects)
{
if(a.Number != currentnumber)
{
currentnumber = a.Number; 
currentList = new List<Object>();
currentList.Add(a);
list.Add(currentList)

}
else
{
currentList.Add(a);
}



}

Something like this would work