2013-08-17 164 views
4

對於具有stringint成員的實體,我有一個IEnumerable<Entityclass>我需要將其轉換爲KeyValuePair<string, double>的數組,反之亦然。將對象轉換爲KeyValuePair

它失敗並出現轉換錯誤。

[DataContract] 
public class Entityclass 
{ 
    [DataMember] 
    public string text{ get; set; } 
    [DataMember] 
    public int textcount{ get; set; } 
} 

IEnumerable<Entityclass>

  • 如何從IEnumerable<Entityclass>轉換的KeyvaluePair<string, double>[]數組?如何將KeyvaluePair<string, double>[]數組轉換爲KeyvaluePair<string, int>[]數組?

  • 如何將KeyvaluePair<string, double>轉換回IEnumerable?

我曾嘗試:

  • topics is IEnumerable<Entityclass>;
  • topics.Cast<KeyValuePair<string, double>>().ToArray();採用鑄造失敗,錯誤
+0

問題標題應該是固定的,它的「轉換一個列表或一個可枚舉到KeyValuePair的數組」不是一個單一的對象 –

回答

18

您需要項目每個主題爲KeyValuePair。 LINQ的Select擴展方法執行的是:

topics 
    .Select(x=> new KeyValuePair<string, double>(x.text, x.textcount)) 
    .ToArray();