2017-06-21 88 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() –

相關問題