I have a big array of 700 groups. I need to sort the array by specific rules:
- We need to sort by company name
- Hierarchy depends on the number of points in the groups.Name
- There are a lot of records with same company name, but the first one to show from specific company must contain
".All". After this record, we need to put all others with the same name ordered by"1." - Specific case when there is a position directly applied to the company
Example:
groups[0].CompanyName = "Acompany"
groups[1].CompanyName = "Acompany"
groups[2].CompanyName = "Acompany"
groups[3].CompanyName = "Acompany"
groups[4].CompanyName = "Acompany"
groups[5].CompanyName = "Bcompany"
groups[6].CompanyName = "Bcompany"
groups[7].CompanyName = "Bcompany"
groups[0].Name = "Acompany.All" //(root)
groups[1].Name = "D.Acompany.example" //this is the specific case (leaf)
groups[2].Name = "Acompany.ABC"//(group)
groups[3].Name = "D.Acompany.ABC.PrimaryTeacher" //(leaf)
groups[4].Name = "Acompany.ABC.Something"//(group)
groups[5].Name = "Bcompany.All" //(root)
groups[6].Name = "Bcompany.Sites"//(group)
groups[7].Name = "Bcompany.Sites.example" //(leaf)
The example shows how the array should look like after sort. It's really complicated, I hope I have managed to explain it.
For now I have achieved:
There are 2 problems :
1.D.A.1stFloor.Cleaner must be under A.1stFloor
2.D.B.Society.Worker must be under B.Society
My code for now :
Array.Sort(groups, (a, b) =>
{
if (a.CompanyName != b.CompanyName)
{
return a.CompanyName.CompareTo(b.CompanyName);
}
if (a.Name.Contains(".All"))
{
return -1;
}
if (b.Name.Contains(".All"))
return 1;
if (a.Name.StartsWith("D.") && a.Name.Count(x => x == '.') == 2)
return -1;
if (b.Name.StartsWith("D.") && b.Name.Count(x => x == '.') == 2)
return 1;
if (a.Name.Count(x => x == '.') == 1)
return -1;
if (b.Name.Count(x => x == '.') == 1)
return 1;
if (a.Name.StartsWith("D") && a.Name.Count(x => x == '.') == 3) //needs to be moved I guess
return -1;
if (b.Name.StartsWith("D") && b.Name.Count(x => x == '.') == 3)//needs to be moved I guess
return 1;
return a.Name.CompareTo(b.Name);
});


D.*is not clear. So it will be hard for anyone to tell you the right algo for sorting. Anyway, is this data dynamic, meaning is it going to change very frequently? I suppose its static data and the grouping / hierarchy is not going to change as such. In which case I will suggest that you add another column to manage the parent - child relationship. It will be a one time activity but it will help you in sorting.D means it's a positioun under a groupand then you are also sayingit can be a group under a other group. That's Confusing. Have you considered using separate column to manage hierarchy?