Tôi có một lớp so sánh 2 trường hợp của cùng một đối tượng và tạo ra một danh sách các khác biệt của chúng. Điều này được thực hiện bằng cách lặp qua các bộ sưu tập chính và điền vào một tập hợp các bộ sưu tập khác với danh sách những gì đã thay đổi (điều này có thể có ý nghĩa hơn sau khi xem mã bên dưới). Điều này làm việc, và tạo ra một đối tượng cho phép tôi biết chính xác những gì đã được thêm vào và loại bỏ giữa đối tượng "cũ" và "mới".
Câu hỏi/mối quan tâm của tôi là ... nó thực sự xấu xí, với hàng tấn vòng và điều kiện. Có cách nào tốt hơn để lưu trữ/tiếp cận điều này, mà không cần phải dựa quá nhiều vào các nhóm vô tận của các điều kiện mã hóa cứng?Xóa các vòng lặp và điều kiện mã hóa lặp đi lặp lại trong C#
public void DiffSteps()
{
try
{
//Confirm that there are 2 populated objects to compare
if (NewStep.Id != Guid.Empty && SavedStep.Id != Guid.Empty)
{
//<TODO> Find a good way to compare quickly if the objects are exactly the same...hash?
//Compare the StepDoc collections:
OldDocs = SavedStep.StepDocs;
NewDocs = NewStep.StepDocs;
Collection<StepDoc> docstoDelete = new Collection<StepDoc>();
foreach (StepDoc oldDoc in OldDocs)
{
bool delete = false;
foreach (StepDoc newDoc in NewDocs)
{
if (newDoc.DocId == oldDoc.DocId)
{
delete = true;
}
}
if (delete)
docstoDelete.Add(oldDoc);
}
foreach (StepDoc doc in docstoDelete)
{
OldDocs.Remove(doc);
NewDocs.Remove(doc);
}
//Same loop(s) for StepUsers...omitted for brevity
//This is a collection of users to delete; it is the collection
//of users that has not changed. So, this collection also needs to be checked
//to see if the permisssions (or any other future properties) have changed.
foreach (StepUser user in userstoDelete)
{
//Compare the two
StepUser oldUser = null;
StepUser newUser = null;
foreach(StepUser oldie in OldUsers)
{
if (user.UserId == oldie.UserId)
oldUser = oldie;
}
foreach (StepUser newie in NewUsers)
{
if (user.UserId == newie.UserId)
newUser = newie;
}
if(oldUser != null && newUser != null)
{
if (oldUser.Role != newUser.Role)
UpdatedRoles.Add(newUser.Name, newUser.Role);
}
OldUsers.Remove(user);
NewUsers.Remove(user);
}
}
}
catch(Exception ex)
{
string errorMessage =
String.Format("Error generating diff between Step objects {0} and {1}", NewStep.Id, SavedStep.Id);
log.Error(errorMessage,ex);
throw;
}
}
Khung nhắm mục tiêu là 3.5.
Khung nhắm mục tiêu là 3.5. – Dan