Michael Hervas

Michael Hervas

  • 2.1k
  • 8
  • 9.6k

Converting Object Properties to Array

Jan 31 2021 12:43 AM
  1. public class myObj    
  2. {    
  3.     public string ob1 { getset; }    
  4.     public string ob2 { getset; }    
  5. }    
  6.     
  7. List<myObj> objlist = new List<myObj>();    
  8.     
  9. objlist.Add(new myObj    
  10. {    
  11.     ob1 = "A",    
  12.     ob2 = "1"    
  13. });    
  14. objlist.Add(new myObj    
  15. {    
  16.     ob1 = "B",    
  17.     ob2 = "2"    
  18. });    
  19.     
  20. List<string[]> converted = MyConvert(objlist);    
  21.     
  22.     
  23. public static List<string[]> MyConvert(List<objlist> mobj)    
  24. {    
  25.     foreach (objlist item in mobj)    
  26.     {    
  27.         string[] arr = ((IEnumerable)item).Cast<objlist>()    
  28.                          .Select(x => x.ToString())    
  29.                          .ToArray();    
  30.     }    
  31. }  
I've been trying to convert the object objlist to a List of string array. I've searched the net and found IEnumerable might help, but I got stopped by an error when I run the program..
 
System.InvalidCastException
HResult=0x80004002
Message=Unable to cast object of type 'objlist' to type 'System.Collections.IEnumerable'.

Answers (5)