-4 c# optimization
我有一小段代码,每个代码都在使用.我已经优化了我的代码,但我的老板希望我进一步优化它.我不知道在这里可以做进一步的优化.
foreach (Match match in matches) {
//When oveeride is false and you have to download all the files
if (Override.Equals(false)) {
//putting the matches from regular expression into DownloadFileStruct oject
df = new DownloadFileStruct(match.Groups[1].Value, match.Groups[2].Value);
//Adding DownloadFileStruct object to a array list
DownloadFileList.Add(df);
}
//When override is true and a paticular file has to be downloaded
else if (match.Groups[2].Value.Equals(OverrideFileName)) {
//putting the matche from regular expression into a DownloadFileStruct oject
df = new DownloadFileStruct(match.Groups[1].Value, match.Groups[2].Value);
//Adding DownloadFileStruct object to a array list
DownloadFileList.Add(df);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的老板说"你不需要'if'和'else if'在两个分支中执行相同的代码".
只需在if中使用OR,而不是重复两次代码.
它不是关于优化,它不需要维护2个完全相同的代码分支.
foreach (Match match in matches) {
//When oveeride is false and you have to download all the files
if (Override.Equals(false) || match.Groups[2].Value.Equals(OverrideFileName)) {
//putting the matches from regular expression into DownloadFileStruct oject
df = new DownloadFileStruct(match.Groups[1].Value, match.Groups[2].Value);
//Adding DownloadFileStruct object to a array list
DownloadFileList.Add(df);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将代码简化为:
foreach (Match match in matches)
{
if (Override && !match.Groups[2].Value.Equals(OverrideFileName))
continue;
df = new DownloadFileStruct(match.Groups[1].Value, match.Groups[2].Value);
DownloadFileList.Add(df);
}
Run Code Online (Sandbox Code Playgroud)
或LINQ-ish:
DownloadFileList =
matches.Cast<Match>()
.Where(x => !Override || x.Groups[2].Value.Equals(OverrideFileName))
.Select(x => new DownloadFileStruct(x.Groups[1].Value,
x.Groups[2].Value))
.ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
177 次 |
| 最近记录: |