我有各种类准备具有匹配格式的结果:对象为列表的列表,对象为列表的列表。这是目标应用程序所必需的。
源数据来自各种系统。这是一个:
var results = new List<object>();
using (var csvReader = new CsvReader(exportFilePath))
{
csvReader.ValueSeparator = '$';
var header = csvReader.ReadHeaderRecord();
foreach (var record in csvReader.DataRecords)
{
var nameValuePairs = new List<object>();
foreach (var column in header.Values)
{
var nameValuePair = new List<object>(2);
nameValuePair.Add(column);
nameValuePair.Add(record[column]);
nameValuePairs.Add(nameValuePair);
}
results.Add(nameValuePairs);
}
}
return results;
这可能是最干净的形式。这是另一个:
var results = new List<object>();
var searchRootPath = "LDAP://OU=Standard Users Accounts,OU=...,DC=local";
var filter = "(&(objectClass=user)(objectCategory=person))";
var propertiesToLoad = new string[] { "sAMAccountName", "employeeNumber",
"mail", "telephoneNumber"};
using (var searchRoot = new DirectoryEntry(searchRootPath))
using (var ds = new DirectorySearcher(searchRoot, filter, propertiesToLoad, SearchScope.OneLevel))
{
ds.PageSize = 100;
using (var src = ds.FindAll())
{
foreach (SearchResult sr in src)
{
var propertyNameValuePairs = new List<object>();
foreach (var property in propertiesToLoad)
{
var propertyNameValuePair = new List<object>(2);
propertyNameValuePair.Add(property);
if (sr.Properties[property].Count == 0)
propertyNameValuePair.Add("<not set>");
else
propertyNameValuePair.Add(sr.Properties[property][0].ToString());
propertyNameValuePairs.Add(propertyNameValuePair);
}
results.Add(propertyNameValuePairs);
}
}
}
return results;
如您所见,结构重复但获取数据的方式不同。例如,在前者中,它是 record[column],但在后者中,它是 sr.Properties[property][0].ToString() (整个 'if' 语句的复杂性);加上加载数据的差异。模板方法是最好的方法还是我错过了什么?