Tho*_*hom 2 c# arrays struct list object
我想制作一个存储的程序,phones如:
Brand: Samsung
Type: Galaxy S3
Price: 199.95
Ammount: 45
-------------------
Brand: LG
Type: Cookie
Price: 65.00
Ammount: 13
-------------------
etc, etc, etc,
Run Code Online (Sandbox Code Playgroud)
这样做的最佳做法是什么?
在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)
)
)
Run Code Online (Sandbox Code Playgroud)
这也是可能的C#,因为我不知道有多少电话在列表中去,和数据类型是不同的:string,decimal,int.我不知道,因为你必须使用什么lists,structs,objects,classes等进一步.
提前致谢!
Tim*_*ter 10
使用类如下的类:
public class Phone
{
public string Brand { get; set; }
public string Type { get; set; }
public decimal Price { get; set; }
public int Amount { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后你可以填充一个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..
};
Run Code Online (Sandbox Code Playgroud)
......或者在一个循环中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);
Run Code Online (Sandbox Code Playgroud)
或者您可以使用列表索引器访问给定索引处的特定电话:
Phone firstPhone = phones[0]; // note that you get an exception if the list is empty
Run Code Online (Sandbox Code Playgroud)
或通过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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12976 次 |
| 最近记录: |