In my MVC3 application I want to create an anonymous collection with fields names like this:
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 in order to send custom post requests during integration testing of my app. How can I declare a an anonymous collection with this field names?
In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.
The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
Use an anonymous collection of anonymous objects, like so:
Licenses = new [] {
new {
IsDeleted = "False",
ID = "6",
AdmissionDate = "2,1999",
AdmissionDate_monthSelected = "2"
} //, ... and so on
}
... and in context: ([edit] Oh, and I didn't see your buyer...)
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"
}
}
}
You could use 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",
}
}
}
Try this:
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 am using a nested anonymous type for buyers and a nested array of yet another anyonymous type for licences. This allows you to access values like this
string name = x.Buyer.Lastname;
string id = x.Licences[0].ID;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With