public Dictionary<string, List<BasicEntity>> ValidateProcess(string excelFile) { var readExcelResp = _excelReader.ReadExcel(excelFile); foreach (var keyValuePair in readExcelResp) { foreach (var basicEntity in keyValuePair.Value) { var validationResult = ExecuteValidate(basicEntity); if (!validationResult.IsValid) { basicEntity.MigrationStatus = MigrationStatus.PreValidationFailed; foreach (var validationResultError in validationResult.Errors) { excelErrorLogService.AddErrorLog(basicEntity.MigrationRowNum.ToString(), validationResultError.ErrorMessage, keyValuePair.Key); } } } if (keyValuePair.Value.Any()) { var verifyDuplicate = VerifyDuplicate(keyValuePair.Value,keyValuePair.Key); if (verifyDuplicate.Any()) { var type = typeof(IValidator<>).MakeGenericType(keyValuePair.Value[0].GetType()); var validator = provider.GetService(type) ; if (validator != null) { var methodInfo = validator.GetType().GetMethod("DuplicateHandler", new[] {verifyDuplicate.GetType() }); methodInfo?.Invoke(validator, new object?[] { verifyDuplicate }); } } } } return readExcelResp; } public List<BasicEntity> VerifyDuplicate(List<BasicEntity> checkList, String sheetName) { var verifySet = new HashSet<string>(); var sameList = new List<BasicEntity>(); var identity = checkList[0].GetIdentity(); if (!string.IsNullOrEmpty(identity)) { var fields = identity.Split(""); foreach (var basicEntity in checkList) { List<string> fieldsValue = new(); foreach (var field in fields) { fieldsValue.Add(basicEntity.GetType() .GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).GetValue(basicEntity) ?.ToString()); } var values = string.Join("", fieldsValue); if (verifySet.Contains(values)) { basicEntity.MigrationStatus = MigrationStatus.PreValidationFailed; sameList.Add(basicEntity); _excelErrorLogService.AddErrorLog(basicEntity.MigrationRowNum.ToString(), $"Fields {identity} values repetition", sheetName); } else { verifySet.Add(values); } } } return sameList; } 优化这段代码
时间: 2024-03-29 09:40:34 浏览: 16
这段代码的优化需要结合实际业务场景和需求,以下是一些可能的优化建议:
1. 提取方法:可以将一些功能类似或者重复使用的代码片段提取出来,封装成方法,提高代码的重用性和可读性。比如可以将 VerifyDuplicate 方法提取出来,作为一个独立的方法。
2. 减少嵌套:可以尝试减少嵌套层数,提高代码的可读性。比如可以将 foreach 循环中的部分代码提取出来,作为一个独立的方法。
3. 异常处理:在代码中需要考虑异常情况的处理。比如在调用 ExecuteValidate 和 VerifyDuplicate 方法时,需要对可能出现的异常情况进行捕获和处理。
4. 代码简化:可以尝试简化代码,减少不必要的复杂度。比如在 VerifyDuplicate 方法中,可以使用 Linq 表达式来简化代码。
5. 代码可测试性:在编写代码时,需要考虑代码的可测试性。可以将某些方法的参数提取出来,作为方法的输入参数,这样可以方便地进行单元测试。
6. 代码风格:在编写代码时,需要遵守一定的代码风格,使代码看起来更加整洁和易读。比如可以使用空格和缩进来分隔代码块,或者使用注释来解释代码的作用和用途。
相关问题
public Dictionary<string, List<BasicEntity>> ValidateProcess(string excelFile) { var readExcelResp = excelReader.ReadExcel(excelFile); foreach (var keyValuePair in readExcelResp) { var errors = new List<BasicEntity>(); foreach (var basicEntity in keyValuePair.Value) { var validationResult = ExecuteValidate(basicEntity); if (validationResult != null && !validationResult.IsValid) { errors.Add(basicEntity); foreach (var validationResultError in validationResult.Errors) { excelErrorLogService.AddErrorLog(basicEntity.MigrationRowNum.ToString(), validationResultError.ErrorMessage, keyValuePair.Key); } } } if (errors.Any()) { keyValuePair.Value.RemoveAll(i => errors.Contains(i)); } if (keyValuePair.Value.Any()) { var verifySet = new HashSet<string>(); var sameList = new List<BasicEntity>(); var identity = keyValuePair.Value[0].GetIdentity(); if (!string.IsNullOrEmpty(identity)) { var fields = identity.Split(""); foreach (var basicEntity in keyValuePair.Value) { List<string> fieldsValue = new(); foreach (var field in fields) { fieldsValue.Add(basicEntity.GetType() .GetField(field, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(basicEntity) ?.ToString()); } var values = string.Join("", fieldsValue); if (verifySet.Contains(values)) { sameList.Add(basicEntity); _excelErrorLogService.AddErrorLog(basicEntity.MigrationRowNum.ToString(), $"Fields {fields} values repetition" , keyValuePair.Key); } else { verifySet.Add(values); } } } } } return readExcelResp; } 优化这段代码
这段代码可以进行以下优化:
1. 使用 LINQ 来简化代码,例如使用 `Where` 和 `Select` 来筛选和映射集合,使用 `Any` 和 `All` 来判断集合是否为空或满足条件。
2. 将重复的代码抽象成方法或者变量,避免代码重复。
3. 使用 `StringBuilder` 来拼接字符串,避免大量的字符串连接操作。
下面是优化后的代码:
```
public Dictionary<string, List<BasicEntity>> ValidateProcess(string excelFile)
{
var readExcelResp = excelReader.ReadExcel(excelFile);
foreach (var keyValuePair in readExcelResp)
{
var errors = keyValuePair.Value
.Select(ExecuteValidate)
.Where(validationResult => validationResult != null && !validationResult.IsValid)
.SelectMany(validationResult => validationResult.Errors.Select(error => (validationResult.BasicEntity, error)))
.ToList();
errors.ForEach(error => _excelErrorLogService.AddErrorLog(error.BasicEntity.MigrationRowNum.ToString(), error.ErrorMessage, keyValuePair.Key));
keyValuePair.Value.RemoveAll(errors.Select(error => error.BasicEntity).Contains);
if (keyValuePair.Value.Any())
{
var identityFields = keyValuePair.Value.FirstOrDefault()?.GetIdentity()?.Split(";");
if (identityFields != null)
{
var sameList = new List<BasicEntity>();
var verifySet = new HashSet<string>();
foreach (var basicEntity in keyValuePair.Value)
{
var values = identityFields.Select(field => basicEntity.GetType().GetField(field, BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(basicEntity)?.ToString()).Aggregate(new StringBuilder(), (sb, value) => sb.Append(value)).ToString();
if (verifySet.Contains(values))
{
sameList.Add(basicEntity);
_excelErrorLogService.AddErrorLog(basicEntity.MigrationRowNum.ToString(), $"Fields {string.Join(",", identityFields)} values repetition", keyValuePair.Key);
}
else
{
verifySet.Add(values);
}
}
keyValuePair.Value.RemoveAll(sameList.Contains);
}
}
}
return readExcelResp;
}
```
easyexcel读取excel写入到list<map>
你可以使用阿里巴巴的EasyExcel开源库来读取Excel文件,并将其写入到List<Map>中。下面是一个示例代码:
```java
public List<Map<String, Object>> readExcel(File file) {
List<Map<String, Object>> list = new ArrayList<>();
ExcelReader excelReader = null;
try {
// 创建 ExcelReader 对象
excelReader = EasyExcel.read(file).build();
// 获取第一个工作表
ReadSheet readSheet = EasyExcel.readSheet(0).build();
// 读取数据并写入到 List<Map> 中
excelReader.read(readSheet).headRowNumber(1).registerReadListener(new ReadListener() {
private List<String> headList;
@Override
public void onReadSheet(int sheetIndex, String sheetName) {
}
@Override
public void onReadRowData(List<String> rowData, AnalysisContext context) {
if (headList == null) {
// 第一行为表头,记录表头信息
headList = rowData;
} else {
// 将每行数据转换为 Map,并添加到 List 中
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < headList.size(); i++) {
map.put(headList.get(i), rowData.get(i));
}
list.add(map);
}
}
@Override
public void onException(Exception exception, AnalysisContext context) {
}
}).doRead();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭 ExcelReader 对象
if (excelReader != null) {
excelReader.finish();
}
}
return list;
}
```
该方法接收一个Excel文件作为参数,并返回一个List<Map>对象。在方法中,我们使用EasyExcel库的read方法创建ExcelReader对象,然后使用readSheet方法获取第一个工作表。接着,我们使用registerReadListener方法注册一个ReadListener实例,该实例在读取Excel文件时会被调用。在ReadListener实例中,我们通过onReadRowData方法读取每一行数据并将其转换为Map对象,最后将Map对象添加到List中。最后,我们关闭ExcelReader对象并返回List<Map>对象。
需要注意的是,该代码使用了Java 8的Lambda表达式语法。如果你使用的是Java 7或更早的版本,请将Lambda表达式替换为匿名内部类。