I have a Dictionary
and I need to convert it into a List
where Data
has the properties lab
.NET already has a data type that does what Data
would do: KeyValuePair<T1,T2>
. Dictionary already implements IEnumerable<KeyValuePair<T1,T2>>
, just cast to it.
Dictionary<string, int> blah = new Dictionary<string, int>();
IEnumerable<KeyValuePair<string, int>> foo = blah;
This is a old post, but post only to help other persons ;)
Example to convert any object type:
public List<T> Select<T>(string filterParam)
{
DataTable dataTable = new DataTable()
//{... implement filter to fill dataTable }
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dataTable.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dataTable.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
string json = new JavaScriptSerializer().Serialize(rows);
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T[]));
var tick = (T[])deserializer.ReadObject(stream);
return tick.ToList();
}
}
I assume that "no loop" actually means "i want LINQ":
List<Data> = dictionary1.Select(
pair => new Data() {
label = pair.Key,
value = pair.Value
})).ToList();