簡體   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