我们如何将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; }
}
业务对象到数据契约Mapper功能: -
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;
}
这给了我
的错误&#34;错误无法隐式转换类型&#39; System.Collections.Hashtable&#39; 至 &#39; System.Collections.Generic.List&#39;&#34;
因为ColorEntry是具有哈希表属性的对象。
我也试过x.Properties.ToList(),但这些也行不通。
答案 0 :(得分:0)
代码中的HashTable
在哪里?我假设它是Properties
类中的属性ColourEntry
。因此,您希望将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;