我似乎无法弄清楚如何重构代码中的特定部分。我已将它从两个单独的方法缩减为单个方法,并将另一个变量(TopOrBottomPercent
)作为标志传递,以确定适当的OrderBy
和Where
子句(因为这些是唯一的两种方法之间的差异)。现在我有两种相同的方式加载DataTable
(一旦过滤)。
以下相关代码:
private object LoadPercentDiffPoP(String TopOrBottomPercent, DateTime prevPeriodStart, DateTime prevPeriodEnd, DateTime currPeriodStart, DateTime currPeriodEnd) {
...
// Populating data from dictionary to grid
if (TopOrBottomPercent.ToLower() == "top") {
foreach (KeyValuePair<string, ReportData> keyValuePair in ReportDataElements.Where(kvp => kvp.Value.CommPercentDiff > 0)
.OrderByDescending(P => P.Value.CommPercentDiff).Take(itemsToReturn)) {
detailTable.Rows.Add(new object[]{
keyValuePair.Value.LocationVar,
keyValuePair.Value.PropertyID,
keyValuePair.Value.Property,
keyValuePair.Value.IndividualID,
keyValuePair.Value.Individual,
keyValuePair.Value.PrevPeriodComm,
keyValuePair.Value.CurrPeriodComm,
keyValuePair.Value.CommPercentDiff
});
}
} else if (TopOrBottomPercent.ToLower() == "lower") {
foreach (KeyValuePair<string, ReportData> keyValuePair in ReportDataElements.Where(kvp => kvp.Value.CommPercentDiff < 0
&& kvp.Value.CommPercentDiff >= Convert.ToDecimal(maxPercentDisplayed)).OrderBy(P => P.Value.CommPercentDiff).Take(itemsToReturn)) {
detailTable.Rows.Add(new object[]{
keyValuePair.Value.LocationVar,
keyValuePair.Value.PropertyID,
keyValuePair.Value.Property,
keyValuePair.Value.IndividualID,
keyValuePair.Value.Individual,
keyValuePair.Value.PrevPeriodComm,
keyValuePair.Value.CurrPeriodComm,
keyValuePair.Value.CommPercentDiff
});
}
}
return detailTable;
}
感谢您的任何帮助,谢谢!
答案 0 :(得分:3)
您可以逐步构建表达式,而不是单个语句:
private object LoadPercentDiffPoP(String TopOrBottomPercent, DateTime prevPeriodStart, DateTime prevPeriodEnd, DateTime currPeriodStart, DateTime currPeriodEnd) {
...
// Populating data from dictionary to grid
IEnumerable<KeyValuePair<string, ReportData>> query = ReportDataElements;
if (TopOrBottomPercent.ToLower() == "top") {
query = query
.Where(kvp => kvp.Value.CommPercentDiff > 0)
.OrderByDescending(P => P.Value.CommPercentDiff);
} else {
query = query
.Where(kvp => kvp.Value.CommPercentDiff < 0 && kvp.Value.CommPercentDiff >= Convert.ToDecimal(maxPercentDisplayed))
.OrderBy(P => P.Value.CommPercentDiff);
}
foreach (KeyValuePair<string, ReportData> keyValuePair in query.Take(itemsToReturn)) {
detailTable.Rows.Add(new object[]{
keyValuePair.Value.LocationVar,
keyValuePair.Value.PropertyID,
keyValuePair.Value.Property,
keyValuePair.Value.IndividualID,
keyValuePair.Value.Individual,
keyValuePair.Value.PrevPeriodComm,
keyValuePair.Value.CurrPeriodComm,
keyValuePair.Value.CommPercentDiff
});
}
return detailTable;
}