How to use complex property names in an anonymous type?

In my MVC3 application, I want to create an anonymous collection with field names as follows:

new { Buyer.Firstname = "Jim", Buyer.Lastname = "Carrey", Phone = "403-222-6487", PhoneExtension = "", SmsNumber = "", Buyer.Company = "Company 10025", Buyer.ZipCode = "90210", Buyer.City = "Beverly Hills", Buyer.State = "CA", Buyer.Address1 = "Address 10025" Licenses[0].IsDeleted = "False", Licenses[0].ID = "6", Licenses[0].AdmissionDate = "2,1999", Licenses[0].AdmissionDate_monthSelected = "2", } 

I want to have this to send custom mail requests while testing my application integration. How can I declare an anonymous collection with these field names?

+6
source share
3 answers

Use an anonymous collection of anonymous objects, for example:

 Licenses = new [] { new { IsDeleted = "False", ID = "6", AdmissionDate = "2,1999", AdmissionDate_monthSelected = "2" } //, ... and so on } 

... and in context: ([edit] Oh, and I have not seen your customer ...)

 new { Buyer = new { Firstname = "Jim", Lastname = "Carrey", Company = "Company 10025", ZipCode = "90210", City = "Beverly Hills", State = "CA", Address1 = "Address 10025", }, Phone = "403-222-6487", PhoneExtension = "", SmsNumber = "", Licenses = new [] { new { IsDeleted = "False", ID = "6", AdmissionDate = "2,1999", AdmissionDate_monthSelected = "2" } } } 
+7
source

You can use the object and collection initializer syntax:

 var anonymousObject = new { Phone = "403-222-6487", PhoneExtension = "", SmsNumber = "", Buyer = new { Firstname = "Jim", Lastname = "Carrey", Company = "Company 10025", ZipCode = "90210", City = "Beverly Hills", State = "CA", Address1 = "Address 10025" }, Licenses = new[] { new { IsDeleted = "False", ID = "6", AdmissionDate = "2,1999", AdmissionDate_monthSelected = "2", } } } 
+6
source

Try the following:

 var x = new { Phone = "403-222-6487", PhoneExtension = "", SmsNumber = "", Buyer = new { Firstname = "Jim", Lastname = "Carrey", Company = "Company 10025", ZipCode = "90210", City = "Beverly Hills", State = "CA", Address1 = "Address 10025" }, Licenses = new[] { new { IsDeleted = "False", ID = "6", AdmissionDate = "2,1999", AdmissionDate_monthSelected = "2"}, new { IsDeleted = "True", ID = "7", AdmissionDate = "17,2001", AdmissionDate_monthSelected = "3"} } }; 

Note. I use nested anonymous types for buyers and a nested array of another anonymous type for licenses. This allows you to access these values.

 string name = x.Buyer.Lastname; string id = x.Licences[0].ID; 
+2
source

Source: https://habr.com/ru/post/926666/


All Articles