我想將一個Dictionary對象列表轉換爲數據集。該列表來自JSON解析器。我決定以此爲契機來了解擴展方法。擴展方法獲取字典列表作爲數據集?
單個字典工程擴展方法,但對詞典列表不「看」我的權利,主要是因爲該呼叫將變爲
DataSet myExampleDataSet = myExampleDictionary.ToDataSet<Dictionary<string,string>,string,string>();
我缺少的東西的方法是什麼?它真的要這麼複雜嗎?我應該在foreach中拋出Dictionary .ToDataSet方法嗎?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
//fixed code below
namespace TT.Utils
{
public static class DictionaryExtensions
{
/// <summary>
/// Dictionary to DataSet
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="currentDictionary"></param>
/// <returns></returns>
public static DataSet ToDataSet<TKey, TValue>(this IDictionary<TKey, TValue> currentDictionary)
{
DataSet exportedDataSet = new DataSet();
DataTable exportedDataTable = exportedDataSet.Tables.Add();
foreach (TKey key in currentDictionary.Keys)
{
exportedDataTable.Columns.Add(key.ToString());
}
DataRow newRow = exportedDataTable.NewRow();
foreach (KeyValuePair<TKey, TValue> entry in currentDictionary)
{
string key = entry.Key.ToString();
string val = string.Empty;
if (entry.Value != null)
{
val = entry.Value.ToString();
}
newRow[key] = val;
}
exportedDataSet.Tables[0].Rows.Add(newRow);
return exportedDataSet;
}
/// <summary>
/// List of dictionaries to dataset
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="currentList"></param>
/// <returns></returns>
public static DataSet ToDataSet<TKey,TValue>(this IList<Dictionary<TKey,TValue> currentList)
{
DataSet exportedDataSet = new DataSet();
DataTable exportedDataTable = exportedDataSet.Tables.Add();
foreach (Dictionary<TKey, TValue> currentDictionary in currentList.Cast<Dictionary<TKey,TValue>>())
{
foreach (TKey key in currentDictionary.Keys)
{
if (!exportedDataTable.Columns.Contains(key.ToString()))
exportedDataTable.Columns.Add(key.ToString());
}
DataRow newRow = exportedDataTable.NewRow();
foreach (KeyValuePair<TKey, TValue> entry in currentDictionary)
{
string key = entry.Key.ToString();
string val = string.Empty;
if (entry.Value != null)
{
val = entry.Value.ToString();
}
newRow[key] = val;
}
exportedDataSet.Tables[0].Rows.Add(newRow);
}
return exportedDataSet;
}
}
}
你'ToDataSet'是把三種類型'<>'。它真的編譯? – xandy 2010-11-15 06:46:11