将包含对象的字典复制到对象数组c#
我有一个类似于将包含对象的字典复制到对象数组c#,c#,asp.net,C#,Asp.net,我有一个类似于Dictionary的字典,是否有任何方法将字典转换为对象数组,其中对象的类将包含两个成员,其中一个是字符串,另一个是作为值对存储在字典中的对象。请帮助 给定一个类: class ClassA { string CustomerId { get; set; } PatientRecords[] Records { get; set; } public ClassA(string name, PatientRecords[] records) {
Dictionary
的字典,是否有任何方法将字典转换为对象数组,其中对象的类将包含两个成员,其中一个是字符串,另一个是作为值对存储在字典中的对象。请帮助 给定一个类:
class ClassA
{
string CustomerId { get; set; }
PatientRecords[] Records { get; set; }
public ClassA(string name, PatientRecords[] records)
{
Name = name;
Records = records;
}
}
我假设collectionofpatientercords
实现了IEnumberable:
var dict=新字典(…)代码>
然后,要获得具有正确值的ClassA数组:
dict.Select(kv => new ClassA(kv.Key, kv.Value.ToArray())).ToArray();
Dictionary
实现IEnumerable
其中T
是KeyValuePair
。要将其展平到一个数组,只需调用IEnuemrable.ToArray
:
Dictionary<string, int> dict = new Dictionary<string, int>() { { "Key1", 0 }, { "Key2", 1 } };
var kvArray = dict.ToArray();
如果没有更多的细节,您可以拥有dictionary.ToArray()
,它可以精确地给出您的描述。即,KeyValuePair
的数组。您还需要什么?我需要以下类的对象的数组[]:类A{string,object}。当前,我在字典中有值,我不希望结果集中有数组以外的任何其他集合类型。字典中的值对包含集合类型的对象,我甚至希望将该集合转换为数组。在我的示例中,int变量是集合的对象,我想将其转换为一个类的数组-->字典-->到-->数组[],其中类包含两个成员:成员1:字符串,成员2:数组[]…成员2是字典中变量的集合类型…我有字典,想将其转换为数组[]类A的,其中类A包含:成员1:string,成员2:dictionary的值对中使用的类数组class A{PatientRecords[],CustomerID string},dictionary包含…dictionary。我想要的是字典中类A的数组。更改为基于您的类给出一个示例。请注意,CollectionOfPatientRecords必须实现IENumber。如果你想要投票或接受。
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
}
)
);