I have the following codes and I would like to write it in a way that I have minimum duplication of codes.
if (Categories != null)
{
bool flag=false;
foreach (dynamic usableCat in Category.LoadForProject(project.ID))
{
foreach (dynamic catRow in Categories)
{
if (usableCat.ID == catRow.ID)
flag = true;
}
if (!flag)
{
int id = usableCat.ID;
Category resolution = Category.Load(id);
resolution.Delete(Services.UserServices.User);
}
}
}
if (Priorities != null)
{
bool flag = false;
foreach (dynamic usableCat in Priority.LoadForProject(project.ID))
{
foreach (dynamic catRow in Priorities)
{
if (usableCat.ID == catRow.ID)
flag = true;
}
if (!flag)
{
int id = usableCat.ID;
Priority resolution = Priority.Load(id);
resolution.Delete(Services.UserServices.User);
}
}
}
Please note that Category and priority do not have a common base type or interface that includes ID.
void DeleteUsable<Ttype>(IEnumerable<Ttype> usables, IEnumerable<Ttype> collection, Func<int, Ttype> load)
{
bool flag = false;
foreach (dynamic usableCat in usables)
{
foreach (dynamic catRow in collection)
{
if (usableCat.ID == catRow.ID)
flag = true;
}
if (!flag)
{
int id = usableCat.ID;
Ttype resolution = load(id);
resolution.Delete(Services.UserServices.User);
}
}
}
Edit: call it:
if (Categories != null)
DeleteUsable(Category.LoadForProject(project.ID), Categories, Categoriy.Load);
if (Priorities != null)
DeleteUsables(Priority.LoadForProject(project.ID), Priorities, Priority.Load);
Let me suggest an alternative approach: Instead of factoring out the flag
thing, use LINQ to remove the need for the flag loop:
if (Categories != null)
{
foreach (var usableCat in Category.LoadForProject(project.ID))
{
if (!Categories.Any(row => usableCat.ID == row.ID))
Category.Load(usableCat.ID).Delete(Services.UserServices.User);
}
}
if (Priorities != null)
{
foreach (var usablePri in Priority.LoadForProject(project.ID))
{
if (!Priorities.Any(row => usablePri.ID == row.ID))
Priority.Load(usablePri.ID).Delete(Services.UserServices.User);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With