我想制作一个存储phones
如下的程序:
Brand: Samsung
Type: Galaxy S3
Price: 199.95
Ammount: 45
-------------------
Brand: LG
Type: Cookie
Price: 65.00
Ammount: 13
-------------------
etc, etc, etc,
最佳做法是什么?
在php
我应该做的:
$phones = array(
array(
array("Brand" => "Samsung"),
array("Type" => "Galaxy S3"),
array("Price" => 199.95),
array("Ammount" => 45)
),
array(
array("Brand" => "LG"),
array("Type" => "Cookie"),
array("Price" => 65.00),
array("Ammount" => 13)
)
)
这也是可能的C#
,因为我不知道有多少手机有要在列表中,数据类型是不同的:string
,decimal
,int
。我不知道,因为你必须使用什么lists
,structs
,objects
,classes
等进一步。
提前致谢!
使用类似的类:
public class Phone
{
public string Brand { get; set; }
public string Type { get; set; }
public decimal Price { get; set; }
public int Amount { get; set; }
}
然后,您可以List<Phone>
使用集合初始值设定项语法来填充,例如:
var phones = new List<Phone> {
new Phone{
Brand = "Samsung", Type ="Galaxy S3", Price=199.95m, Amount=45
},
new Phone{
Brand = "LG", Type ="Cookie", Price=65.00m, Amount=13
} // etc..
};
...或与循环List.Add
。
填写完列表后,您可以循环播放一次一次获取一部电话
例如:
foreach(Phone p in phones)
Console.WriteLine("Brand:{0}, Type:{1} Price:{2} Amount:{3}", p.Brand,p.Type,p.Price,p.Amount);
或者您可以使用列表索引器以给定索引访问特定电话:
Phone firstPhone = phones[0]; // note that you get an exception if the list is empty
或通过LINQ扩展方法:
Phone firstPhone = phones.First();
Phone lastPhone = phones.Last();
// get total-price of all phones:
decimal totalPrice = phones.Sum(p => p.Price);
// get average-price of all phones:
decimal averagePrice = phones.Average(p => p.Price);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句