[英]How to set a array of object inner a class property
我需要创建一个 object 来返回一个 json ,如下所示:
{
"Name": "John",
"Age": 25,
"Products": [
{
"Code": "1",
"Price": 400.00
},
{
"Code": "2",
"Price": 100.00
},
{
"Code": "32",
"Price": 250.00
},
],
}
我怎样才能做到这一点? :/我只需要创建一个 object 并转换为 json... 我知道如何转换,但不知道如何使用“对象数组”填充产品 model
我的 Model Class:
public class Customer
{
public string Name { get; set; }
public string Age { get; set; }
public Products[] Products { get; set; }
}
public class Products
{
public string Code { get; set; }
public string Price { get; set; }
}
我填充数据的程序:(在这里您可以看到一个示例填充客户 model 10 次和产品 model 3 次)
List<Object> customerList = new List<Object>();
List<Object> productList = new List<Object>();
for (int i = 0; i < 10; i++)
{
Customer customer = new Customer();
customer.Name = "Pedro";
customer.Age = "20";
for (int ii = 0; ii < 3; ii++)
{
Product product = new Product();
product.Code = "1";
product.Price = "400.00";
productList.Add(product);
}
customer.Product = // Why I need to do here?
customerList.Add(customer);
}
您已经在列表中拥有产品,因此您只需将其转换为数组以匹配属性类型:
customer.Products = productList.ToArray();
当然,您应该将声明更改为:
List<Product> productList = new List<Product>();
如果您出于任何原因不想更改声明?:您可以这样做:
customer.Products = productList.Select(x => (Product)x).ToArray();
对此的简短回答:
customer.Product = // Why I need to do here?
只是您需要将您的产品添加为Product[]
(因为这是在Customer
类中定义的方式),我们可以通过将列表中的项目转换为Product
来做到这一点(因此我们获得强类型对象而不仅仅是Object
对象)并使用System.Linq
扩展方法ToArray()
从列表中创建一个数组:
customer.Product = productList.Select(p => (Product)p).ToArray();
// Note that we should clear our list for the next iteration
productsList.Clear();
还有一些需要考虑的事情:
类不应以复数命名,除非它们是 collections,因此您的Products
class 应命名为Product
。
当您有可用的强类型类时,您应该避免使用object
列表,因此List<Object> customerList
应该是List<Customer> customers
。
您一遍又一遍地填充相同数据的列表。 我认为这是因为这只是一个示例,但想让您知道以防万一。
您现有的代码可以修改为:
List<Customer> customers = new List<Customer>();
for (int i = 0; i < 10; i++)
{
// Create a new customer
Customer customer = new Customer
{
Name = "Pedro",
Age = "20",
};
// Create an array of products since Customer expects this type
Product[] products = new Product[3];
for (int j = 0; j < products.Length; j++)
{
products[j] = new Product
{
Code = "1",
Price = "400.00"
};
}
// Add the array to our customer
customer.Products = products;
// Add our customer to the list
customers.Add(customer);
}
或者我们可以使用纯 Linq 和 select 我们的数据,使用Enumerable.Range
作为“循环”构造:
List<Customer> customers = Enumerable.Range(0, 10).Select(c =>
new Customer
{
Name = "Pedro",
Age = "20",
Products = Enumerable.Range(0, 3).Select(p => new Product
{
Code = "1",
Price = "400.00"
}).ToArray()
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.