Working with C# Anonymous Types

前端 未结 8 1524
感动是毒
感动是毒 2020-11-29 12:56

I am calling a method that returns a List variable that contains a c# Anonymous Type objects. For example:

List list = new List()         


        
      
      
      
8条回答
  •  再見小時候
    2020-11-29 13:30

    You cannot do this with anonymous types. Just create a Contact class/struct and use that.

    List list = new List();
    foreach ( Contact c in allContacts ) {
        list.Add( c );
    }
    
    
    

    Then you can do this:

    foreach ( var o in list ) {
        Console.WriteLine( o.ContactID );
    }
    

    ...or this:

    foreach ( object o in list ) {
        Console.WriteLine( ((Contact)o).ContactID ); //Gives intellisense
    }
    

    Of course you should in that case just do create a Contact list instead of an object list:

    List list = new List();
    foreach ( Contact c in allContacts ) {
        list.Add( c );
    }
    

    EDIT: Missed essential part of the question. Now fixed.
    EDIT: Changed answer yet again. See above.

    提交回复
    热议问题