C# : how to get anonimous properties length ?

To get the number of the properties contained by an objects collection (even Anonymous) like the following:

var data = new []
{ new { Name="Ram", Email="ram@techbrij.com", Phone="111-222-3333" }, new { Name="Shyam", Email="shyam@techbrij.com", Phone="159-222-1596" }, new { Name="Mohan", Email="mohan@techbrij.com", Phone="456-222-4569" }, new { Name="Sohan", Email="sohan@techbrij.com", Phone="789-456-3333" }, new { Name="Karan", Email="karan@techbrij.com", Phone="111-222-1234" }, new { Name="Brij", Email="brij@techbrij.com", Phone="111-222-3333" }

We can use the Type.GetProperties method on this way:

// In this example 'collectionLength' contains 3
int collectionLength = data[0].GetType().GetProperties().Length;

This code works even on Net Core.

Marwen Mselmi
Author: Marwen Mselmi

Founder of Javatuto.com, love Java and open source stuff. Follow me on Linkedin.

Leave a comment