Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 917
Justin Homes Avatar asked Aug 17 '13 03:08

Justin Homes


People also ask

How do you turn an object into an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .

How do you turn an object into a string?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

Can we convert object to string in Java?

We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.


1 Answers

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();
like image 85
King King Avatar answered Sep 22 '22 05:09

King King