繁体   English   中英

将数据存储在数组,对象,结构,列表或类中。 C#

[英]Store data in array, object, struct, list or class. C#

我想制作一个存储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#也是可能的,因为我不知道列表中有多少手机,并且数据类型不同: stringdecimalint 我不知道该使用什么因为你有listsstructsobjectsclasses等等。

提前致谢!

使用类如下的类:

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

最佳解决方案是创建您的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

你会有一个模型类,比如

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},
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM