Working with C# Anonymous Types

前端 未结 8 1536
感动是毒
感动是毒 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:32

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

    this will work only if list is IEnumerable, like this:

    var list = allContacts.Select(c => new {
            ContactID = c.ContactID,
            FullName = c.FullName
        });
    }
    

    but you can't return anonymous types, because you must define return type (you can't return var) and anonymous types can't have names. you should create non-anonymous type if you with to pass it. Actually anonymous types should not be used too much, except for inside of queries.

提交回复
热议问题