Search code examples
c#.netlinq.net-4.0keyvaluepair

Convert object to KeyValuePair


I have an IEnumerable<Entityclass> for an entity that has a string and an int member. i need to convert it to an array of KeyValuePair<string, double> and vice versa.

It fails with a cast error.

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

I have IEnumerable<Entityclass>

  • How do I convert from IEnumerable<Entityclass> to an array of KeyvaluePair<string, double>[]?

  • How do I convert the KeyvaluePair<string, double>[] array to a KeyvaluePair<string, int>[] array ?

  • How do I convert KeyvaluePair<string, double> back to an IEnumerable?

I have tried:

  • topics is IEnumerable<Entityclass>;
  • topics.Cast<KeyValuePair<string, double>>().ToArray(); Fails with cast error

Solution

  • You need to project each topic into a KeyValuePair. The Linq Select extension method does that:

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