Convert an object to KeyValuePair

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

Failure on error.

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

I have an IEnumerable<Entityclass>

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

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

  • How to convert KeyValuePair<string, double> back to IEnumerable?

I tried:

  • topics is IEnumerable<Entityclass>;
  • topics.Cast<KeyValuePair<string, double>>().ToArray(); Error Failure
+4
source share
1 answer

You need to project each theme in KeyValuePair . The Linq Select extension method does this:

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

Source: https://habr.com/ru/post/1497537/


All Articles