我正在寻找一种将包含动态对象的<?php
require 'vendor/autoload.php';
use Medoo\Medoo;
$database = new Medoo([
'database_type' => 'mssql',
'database_name' => 'name',
'server' => 'localhost',
'username' => 'your_username',
'password' => 'your_password'
]);
$result = $database->select("account", [
"user_name",
"email"
];
转换为字典的方法,该字典的键是属性名,值是该属性的不同值。
当前我使用了这段代码,但是我觉得必须有一种更优雅/更快的方式来做到这一点?
List<object>
答案 0 :(得分:0)
批准探针的方式很好,但是您需要进行一些更改以使该方法更快。
private static Dictionary <Type, List <PropertyInfo>> Props = new Dictionary<Type, List<PropertyInfo>> ();
public Dictionary <string,IList<String>> Convert(List <object> records) {
var result = new Dictionary <string,IList <string>>();
foreach(object record in records) {
if (!Props.ContainsKey(record.GetType()))
Props.Add(record.GetType(), record.GetType().GetProperties());
foreach(var prop in Props[record.GetType()]) {
var colValue = prop.GetValue(record, null);
if (colValue != null) {
if (result.ContainsKey(prop.Name)) {
result[prop.Name].Add(colValue.ToString());
}
else {
result.Add(prop.Name, new List <string> () {colValue.ToString()});
}
}
}
}
return result;
}
答案 1 :(得分:0)
您是否正在寻找类似的东西?
var result = properties.ToDictionary(
keySelector: propertyName => propertyName,
elementSelector: propertyName => records
.Select(record => record.GetType().GetProperty(propertyName)?.GetValue(record, null).ToString())
.Where(colValue => colValue != null));