【发布时间】:2021-02-06 18:35:06
【问题描述】:
你怎么能把任意一个 Dictionary
我必须完成这项任务,以便在我的一个应用程序中使用存储在几个自定义对象的属性中的数据填充 ComboBox。
【问题讨论】:
-
您是否希望创建单个列
DataTable?
标签: c# linq dictionary datatable
你怎么能把任意一个 Dictionary
我必须完成这项任务,以便在我的一个应用程序中使用存储在几个自定义对象的属性中的数据填充 ComboBox。
【问题讨论】:
DataTable?
标签: c# linq dictionary datatable
这就是我如何做到这一点的。此方法使用我自己的自定义“IsNullOrEmpty”和“LogError”方法。如果您愿意,您可以删除这些引用或将其替换为您自己的。
我在我的应用程序中使用它,通过使用 Linq 自动将我可能拥有的任何类型的任何随机字典转换为通用 Dictionary
DictionaryOfObjectsToDataTable(districts.ToDictionary(p => (object)p.Key, p => (object)p.Value), "KeyNameHere");
这是完成这项工作的主要方法的代码:
/// <summary>
/// Turns a generic dictionary of object into a datatable, by assuming that the key is the Primary Key column, and the Object's properties are the columns
/// </summary>
/// <param name="input">The input Dictionary</param>
/// <param name="keyName">The Name to give to the Primary Key of the table, the Key of the Dictionary</param>
/// <returns></returns>
public static DataTable DictionaryOfObjectsToDataTable(Dictionary<object, object> input, string keyName)
{
try
{
//Inspect the first object to see if it's a valid object, if not, error out
if (IsNullOrEmpty(input.First().Value)) throw new Exception("First value in the dictionary was not a valid object. Unable to use dictionary.");
DataTable output = new DataTable();
//Add the keys as the first column and set it as the primary key
DataColumn key = new DataColumn(keyName);
output.Columns.Add(key);
output.PrimaryKey = new DataColumn[] { key };
foreach (KeyValuePair<object, object> kvp in input)
{
DataRow dr = output.NewRow();
dr[keyName] = kvp.Key;
foreach (PropertyInfo pi in kvp.Value.GetType().GetProperties())
{
if (!output.Columns.Contains(pi.Name)) output.Columns.Add(pi.Name);
dr[pi.Name] = pi.GetValue(kvp.Value, null);
}
output.Rows.Add(dr);
}
return output;
}
catch (Exception ex)
{
LogError(ex);
return null;
}
}
我只是想与将来可能需要解决类似问题的任何人分享。
【讨论】:
GetProperties 缓存在kvp 循环之外,并在添加每一列时输入类型。
Contains 搜索每一行。