从子类中获取值

时间:2015-10-17 18:34:50

标签: c# list

我有两个班级:

public class ShopClass
    {
        public string shop_id { get; set; }
        public List<CurrencyAmount> amount { get; set; }
    }


public class CurrencyAmount
    {
        public string currency { get; set; }
        public int? amount { get; set; }
    }

我可以像这样在类ShopClass中添加值:

ShopClass shop = new ShopClass();
        shop.shop_id = "100";
        List<CurrencyAmount> ca = new List<CurrencyAmount>();
        ca.Add(new CurrencyAmount() { currency = "USD", amount = 1000});
        shop.amount = ca;

我可以像这样得到shop_id的值:

Console.WriteLine(shop.shop_id);

但我怎样才能获得金额的价值?

非常感谢任何建议。

3 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

foreach (var v in shop.amount)
{
    Console.WriteLine(v.currency + " " + v.amount);
}

或者,您可以避免字符串连接(感谢PC Luddite)并使用:

foreach (var v in shop.amount)
{
    Console.WriteLine("{0} {1}", v.currency, v.amount);
}

此代码段会打印出shop.amount中的所有值。由于shop.amount引用了一个列表,因此您无法使用Console.WriteLine(shop.amount)获取值,因为这只会打印出对列表的引用。相反,您需要遍历shop.amount中的所有项目才能获取其值。

答案 1 :(得分:0)

没有“该”金额,您有一个金额列表。因此,您需要迭代或投影amount属性中的项目,例如使用foreach循环:

foreach (var amount in shop.amount)
{
    Console.WriteLine("{0} {1}", amount.currency, amount.amount);
}

答案 2 :(得分:0)

您的示例可以轻松缩减为字典以进行直接查找。我假设您正在寻找特定货币的价值而不是打印所有价值。

存储货币及其价值。

using System;
using System.Collections.Generic;

public class ShopClass
{
    public ShopClass()
    {
        Amounts = new Dictionary<string, int>();
    }

    public string ShopID { get; set; }
    public Dictionary<string, int> Amounts { get; private set; }

    public void AddAmount(string currency, int amount)
    {
        if (Amounts.ContainsKey(currency))
        {
            Amounts[currency] = amount;
        }
        else
        {
            Amounts.Add(currency, amount);
        }
    }

    public int? GetAmount(string currency)
    {
        if (Amounts.ContainsKey(currency))
        {
            return Amounts[currency];
        }

        return null;
    }

    public void PrintAmounts()
    {
        foreach (var currency in Amounts.Keys)
        {
            Console.WriteLine("{0} - {1}: {2}", ShopID, currency, GetAmount(currency));
        }
    }
}

打印货币值。

ShopClass shop = new ShopClass();
shop.ShopID = "100";
shop.AddCurrency("USD", 1000);
shop.PrintAmounts();