我有以下代码,我想以一种方式编写它,我有最少的代码行,工作以相同的方式完成.我怎样才能做到这一点?
List<Category> categoryList = new List<Category>();
categoryList = Category.LoadForProject(project.ID).ToList();
List<string> categories = new List<string>(Categories);
IList<Category> currentCategories = Category.LoadForProject(project.ID).ToList();
if (currentCategories != null)
{
foreach (var existingCategories in currentCategories)
{
if (categories.Contains(existingCategories.Name))
categories.Remove(existingCategories.Name);
else
existingCategories.Delete(Services.UserServices.User);
}
foreach (string item in categories)
{
Category category = new Category(project, item.ToString());
category.Project = project;
category.Save();
}
}
Run Code Online (Sandbox Code Playgroud)
List<string> priorities = new List<string>(Priorities);
IList<Priority> currentPriorities = Priority.LoadForProject(project.ID).ToList();
if (currentPriorities != null)
{
foreach (var existingPriorities in currentPriorities)
{
if (priorities.Contains(existingPriorities.Name))
priorities.Remove(existingPriorities.Name);
else
existingPriorities.Delete(Services.UserServices.User);
}
foreach (string item in priorities)
{
Priority priority = new Priority(project, item.ToString());
priority.Project = project;
priority.Save();
}
}
Run Code Online (Sandbox Code Playgroud)
这样的事情应该这样做:
public IList<T> DoYourThing<T>(IList<T> items, IList<T> currentItems, Project project) where T : CommonBaseType
{
if (currentItems != null)
{
foreach (var existingItem in currentItems)
{
if (items.Contains(existingItem.Name))
items.Remove(existingItem.Name);
else
existingItems.Delete(Services.UserServices.User);
}
foreach (string item in items)
{
T newItem = Activator.CreateInstance(typeof(T), new object[] {project, item.ToString()}) as T;
newItem.Project = project;
newItem.Save();
}
}
return currentItems;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样调用它:
var currentCategories = DoYourThing(Categories.ToList(), Category.LoadForProject(project.ID).ToList());
var currentProjects = DoYourThing(Priorities.ToList(), Priority.LoadForProject(project.ID).ToList());
Run Code Online (Sandbox Code Playgroud)
最后,您应该特别注意两件事:首先,函数有一个通用条件where T : CommonBaseType.我假设Category和Project有一个包含Name的公共基类型或接口.如果没有,你应该摆脱条件,并使用动态来获取名称.
其次,我正在使用Activator.Create为您创建类.如果你不知道这个伎俩,这是很难弄清楚的棘手部分
祝好运!