将包含对象的字典复制到对象数组c#

时间:2012-04-14 02:16:13

标签: c# asp.net

我有一个类似Dictionary<string,Object>的字典,有没有将Dictionary转换为对象数组的方法,其中对象的类将包含两个成员 - 其中一个将是字符串,另一个将是作为字典中的值对存储的对象。请帮助!!! ..

2 个答案:

答案 0 :(得分:1)

Dictionary<TKey, TValue>实施IEnumerable<T>,其中TKeyValuePair<TKey, TValue>。要将其展平为数组,只需要调用IEnuemrable<T>.ToArray

Dictionary<string, int> dict = new Dictionary<string, int>() { { "Key1", 0 }, { "Key2", 1 } };
var kvArray = dict.ToArray();

kvArray将是一个数组对象,它引用dict中每个元素的键和值作为同一对象的两个独立成员。

你的问题有点含糊不清,也许进一步的解释会帮助我们找到更合适的解决方案。


重新评论,LINQ对此有好处:

Dictionary<string, int[]> dict = new Dictionary<string, int[]>() { { "Key1", new int[] { 0, 1, 2 } }, { "Key2", new int[] { 4, 5, 6 } } };

var pairs = dict.SelectMany(pair => pair.Value
                .Select(v => 
                    new { 
                        Key = pair.Key, 
                        Value = v 
                    }
                 )
             );

答案 1 :(得分:0)

给出一个课程:

class ClassA
{
    string CustomerId { get; set; }
    PatientRecords[] Records { get; set; }

    public ClassA(string name, PatientRecords[] records)
    {
        Name = name;
        Records = records;
    }
}

我假设CollectionOfPatientRecords实现IEnumerable:

var dict = new Dictionary<string, CollectionOfPatientRecords> ( ... );

然后使用正确的值获取A类数组:

dict.Select(kv => new ClassA(kv.Key, kv.Value.ToArray())).ToArray();