'Convert' Dictionary into List<object>

前端 未结 9 1882
感情败类
感情败类 2021-02-20 16:12

I have a Dictionary dictionary1 and I need to convert it into a List where Data has the properties lab

相关标签:
9条回答
  • 2021-02-20 16:50

    .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;
    
    0 讨论(0)
  • 2021-02-20 16:53

    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();
        }
    }
    
    0 讨论(0)
  • 2021-02-20 16:54

    I assume that "no loop" actually means "i want LINQ":

    List<Data> = dictionary1.Select(
        pair => new Data() {
            label = pair.Key,
            value = pair.Value
        })).ToList();
    
    0 讨论(0)
提交回复
热议问题