CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Convert Object Properties to Array

  1. #1
    Join Date
    Jan 2021
    Posts
    2

    Convert Object Properties to Array

    .NET4.8.04084 - VS 2019

    Code:
    public class myObj
    {
    	public string ob1 { get; set; }
    	public string ob2 { get; set; }
    }
    
    List<myObj> objlist = new List<myObj>();
    
    objlist.Add(new myObj
    {
    	ob1 = "A",
    	ob2 = "1"
    });
    objlist.Add(new myObj
    {
    	ob1 = "B",
    	ob2 = "2"
    });
    
    List<string[]> converted = MyConvert(objlist);
    
    
    public static List<string[]> MyConvert(List<objlist> mobj)
    {
    	foreach (objlist item in mobj)
    	{
    		string[] arr = ((IEnumerable)item).Cast<objlist>()
    						 .Select(x => x.ToString())
    						 .ToArray();
    	}
    }
    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'.

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,477

    Re: Convert Object Properties to Array

    Code:
    public class MyObj
        {
            public string Obj1 { get; set; }
            public string Obj2 { get; set; }
        }
        class Program
        {
            static void Main(string[] args)
            {
                var objList = new List<MyObj>
                {
                    { new MyObj { Obj1 = "A", Obj2 = "1" } },
                    { new MyObj { Obj1 = "B", Obj2 = "2" } }
                };
    
                var index = 1;
                foreach(var obj in MyConvert(objList))
                {
                    Console.WriteLine($"Obj: {index++}");
    
                    foreach(var s in obj)
                    {
                        Console.WriteLine($"  {s}");
                    }
                }
            }
    
            static List<string[]> MyConvert(List<MyObj> list)
            {
                var retList = new List<string[]>();
    
                foreach(var obj in list)
                {
                    retList.Add(new string[] { obj.Obj1, obj.Obj2 } );
                }
    
                return retList;
            }
    Outputs:
    Code:
    Obj: 1
      A
      1
    Obj: 2
      B
      2

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)