2014-10-02 62 views
2

我要让存储phones像一个程序:
将数据存储在数组,对象,结构,列表或类中。 C#

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#,因为我不知道有多少电话在列表中去,和数据类型是不同的:stringdecimalint。 我不知道该用什么,因为你有lists,structs,objects,classes等等。

在此先感谢!

回答

6

使用一个类,如:

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>,例如与collection initializer语法:

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); 
+0

要积极主动并为其他数据添加字符串(特殊优惠,回扣,html链接,你的名字) – 2014-10-02 08:41:21

+0

@pe:我可以添加数百万其他东西,比如重写'ToString'或'Equals' +'GetHashCode' ,从'string'或..or ..解析。但它只会分散基本的注意力。我认为OP很聪明,可以理解这个概念。 – 2014-10-02 08:43:33

+0

这不是批评,而是对OP的建议。你的答案接近完美(不开玩笑)。 – 2014-10-02 08:45:47

1

你将有一个模型类,像

class Phone 
{ 
    public string Brand {get; set;} 
    public string Type {get; set;} 
    public decimal Price {get; set;} 
    public int Amount {get; set;} 
} 

然后创建手机的列表,你可以使用这样的代码

var phones = new List<Phone> 
{ 
    new Phone{Brand = "Samsung", Type = "Galaxy S3", Price = 199.95, Amount = 45}, 
    new Phone{Brand = "LG", Type = "Cookie", Price = 65.00, Amount = 13}, 
} 
+0

结构也可以做类似的工作,正如其他答案中所解释的那样,列表(数组)也可以用作对象集合 – 2014-10-02 09:03:23

+0

@AliKazmi Structures可以用作struct,但是这将是一个糟糕的选择。 “电话”数据类型更像C#术语中的“类”。不知道你有什么意见。 – oleksii 2014-10-02 09:40:10

2

最好的解决方案是创建Phone object,如:

public class Phone { 
    public string Brand { get; set; } 
    public string Type { get; set; } 
    public decimal Price { get; set; } 
    public decimal Ammount { get; set; } 
} 

和存储该对象列表中(例如):

List<Phone> phones = new List<Phone>(); 
phones.Add(new Phone { Brand = "Samsung", Type = "Galaxy S3", Price = 199.95, Amount = 45 }); 
etc 
相关问题