I have the following array, which represents the items I'm trying to remove from a certain data structure instance:
string[] diseasesToRemove = new string[] { "D1", "D3", "D5" };
I'm able to do it using the following:
for (int i = 0; i < healthGroup.DiseaseGroups.Length; i++)
{
var dgDiseases = new List<Disease>(healthGroup.DiseaseGroups[i].Diseases);
for (int j = 0; j < dgDiseases.Count; j++)
{
if (diseasesToRemove.Contains(dgDiseases[j].Name))
{
dgDiseases.RemoveAt(j);
j--;
}
}
healthGroup.DiseaseGroups[i].Diseases = dgDiseases.ToArray();
}
However, I'm sure there's a better way using Linq or something else. Is there?
Here are the classes:
public class HealthGroup
{
public DiseaseGroup[] DiseaseGroups { get; set; }
public HealthGroup(DiseaseGroup[] diseaseGroups)
{
DiseaseGroups = diseaseGroups;
}
}
public class DiseaseGroup
{
public string Name { get; set; }
public Disease[] Diseases;
public DiseaseGroup(string name, Disease[] diseases)
{
Name = name;
Diseases = diseases;
}
}
public class Disease
{
public string Name { get; set; } = "My Disease";
public int Risk { get; set; } = 7;
public Disease(string name, int risk)
{
Name = name;
Risk = risk;
}
public override string ToString()
{
return $"{Name} with risk {Risk}";
}
}
And some boilerplate to generate the instance:
Disease d1 = new Disease("D1", 1);
Disease d2 = new Disease("D2", 2);
Disease d3 = new Disease("D3", 3);
Disease d4 = new Disease("D4", 4);
Disease d5 = new Disease("D5", 5);
Disease d6 = new Disease("D6", 6);
Disease d7 = new Disease("D7", 7);
DiseaseGroup dg1 = new DiseaseGroup("DG1", new Disease[] { d1, d2 });
DiseaseGroup dg2 = new DiseaseGroup("DG2", new Disease[] { d3, d4, d5 });
DiseaseGroup dg3 = new DiseaseGroup("DG3", new Disease[] { d6, d7 });
HealthGroup healthGroup = new HealthGroup(new DiseaseGroup[] { dg1, dg2, dg3 });