使用LINQ查找字符串

时间:2017-12-29 21:06:29

标签: c# linq

经过对C#的一些研究和一些使用简单示例的LINQ测试。我想将这些知识运用到我的问题中。

从变量屏幕(Visual Studio)看到的我的DataStructure

- wm
   - Nations
      - [0]
          - Name "USA"
          - stockpile 
            - [0]
                - Name "Coal"
                - Quantity "quantity"
                - Value "value"
      - [1] //Same as above

我尝试访问“煤炭”一直是:

var result = wm.Nations.Find(r => r.Name == "USA")
Console.WriteLine(result + " Result");

但只返回作为对象的[EconomyTest.NationBuilder]。如何从该对象中提取字符串或至少指向美国并访问库存?

Edit1:数据结构声明

    //Declarations of Lists
    public List<ResourceTemplate> stockpile = new List<ResourceTemplate>();
    public List<Money> money = new List<Money>();
    public List<PopulationTemplate> population = new 
    List<PopulationTemplate>();

   public NationBuilder(string name)//Constructor 
    {
        this.Name = name;

        stockpile = new List<ResourceTemplate>();
        money = new List<Money>();
        population = new List<PopulationTemplate>();
    }
    //World Market (Where the actual storage happens)

    public WorldMarket()//Constructor
    {
       //Declaration list 
       Nations = new List<NationBuilder>();
    }

    internal List<NationBuilder> Nations {get; set;}

    public void AddToWorldMarket(NationBuilder nation)
    {
        Nations.Add(nation);
    }

    //Finally how it is managed/used:

    WorldMarket wm = new WorldMarket();//Helps with adding those newly 
    created nations into a List

        foreach (string name in NationNames)
        {
            NationBuilder nation = new NationBuilder(name);//Creates new 
            Objects nations and used the name provided before
            nation.AddResource("Coal", 500, 10);
            nation.AddResource("Water", 100, 10);
            nation.AddMoney(100);
            nation.AddPopulation(1000);

            wm.AddToWorldMarket(nation);

Edit2:评论中提到的功能

    public void AddResource(string itemName, int quantity,  float 
                         value)//Adds Resources to the stockpile
     {
    stockpile.Add(new ResourceTemplate {Name = itemName, Quantity = 
                                      quantity, Value = value });
     }

2 个答案:

答案 0 :(得分:0)

只需指定Name

即可
Console.WriteLine(result.Name + " Result");

要访问stockpile,您可以对其进行迭代;

foreach (var stock in result.stockpile)
{
    //stock.Name
}

答案 1 :(得分:0)

您的整个result变量刚刚被写入控制台,因为它只是调用了它的ToString方法来呈现它,我想你想要的是:

Console.WriteLine(result.Name + " Result");

或者,如果您希望对象在呈现给控制台时显示更多内容,您可以自己覆盖ToString

public override string ToString()
{
   return this.Name + ", stockpile count: " + this.stockpile.Length;
}