2017-06-21 153 views
-3

如何将Hashtable转换为对象列表?可能吗?将Hashtable转换为对象列表

业务对象: -

[Serializable] 
public class ColourEntry 
{ 
    public string Id 
    { 
     get { return this.id; } 
     set { this.id= value; } 
    } 
    public string Name 
    { 
     get { return this.name; } 
     set { this.name= value; } 
    } 
    public Hashtable Properties 
    { 
     get { return this.properties; } 
     set { this.properties = value; } 
    } 
} 

数据合同: -

[DataContract(Name = "Color", Namespace = Constants.Namespace)] 
public class ColorContract 
{ 
    [DataMember(EmitDefaultValue = false)] 
    public string Id { get; set; } 

    [DataMember(EmitDefaultValue = false)] 
    public string Name { get; set; } 

    [DataMember(EmitDefaultValue = false)] 
    public List<PropertiesContract> Properties { get; set; } 
} 

[DataContract(Name = "Properties", Namespace = Constants.Namespace)] 
public class PropertiesContract 
{ 
    [DataMember(EmitDefaultValue = false)] 
    public string Key { get; set; } 

    [DataMember(EmitDefaultValue = false)] 
    public string Value { get; set; } 
} 

业务对象的数据合同映射功能: -

public static List<ColorContract> MapContract(IList<ColourEntry> colourEntryList) 
{ 
    var colorContract = colourEntryList.Select(x => new ColorContract() 
    { 
     Id = x.Id.ToDisplayString(), 
     Name = x.Name, 
     Properties = x.Properties 
    } 
    return colorContract; 
} 

这给我的

错误

“错误无法隐式转换类型‘System.Collections.Hashtable’ 到 ‘System.Collections.Generic.List’”

因为ColorEntry是具有性质为散列表对象。

我也试过x.Properties.ToList()但这些也不起作用。

+1

显示什么'ColourEntry.Properties'是。散列表由键和值组成。 – HimBromBeere

+1

代码中的HashTable在哪里?我假设它是'ColourEntry'类中属性'Properties',你没有显示(!)。 –

+0

你在哪里使用MapContract? –

回答

0

代码中的HashTable在哪里?我认为这是ColourEntry类中的属性Properties。所以你想要将HashTable转换为List<PropertiesContract>

我想这是你想要的(hashTable.Cast<DictionaryEntry>):

var colorContract = colourEntryList.Select(x => new ColorContract() 
{ 
    Id = x.Id.ToDisplayString(), 
    Name = x.Name, 
    Properties = x.Properties 
     .Cast<DictionaryEntry>() 
     .Select(kv => new PropertiesContract{ Key = kv.Key.ToString(), Value = kv.Value?.ToString() }) 
     .ToList() 
} 
return colorContract; 
+0

感谢您的回复。此解决方案适用于小修改 Properties = x.Properties.Cast ()。Select(kv => new PropertiesContract {Key = kv.Key.ToString(),Value = kv.Value.ToString()})。 ToList() –