簡體   English   中英

計算和訪問列表列表中的項目,即:含訂單項的發票

[英]Counting and accessing items in a list of lists ie: invoice with line items

我試圖圍繞C#列表,這來自強大的PHP背景並以PHP Array術語來思考,但是我有一個包含列表的類,並且試圖計算其中的不連續項。 有沒有簡單的linq方法可以做到這一點,還是我會使用某種嵌套的foreach?

先感謝您

public void main() {
   List<invoice> inv = new List<invoice>();

   // I do something that populates inv with, say 100 invoices

   // Count distinct inv.lines.rowtype ?? to get:
   Type A   34
   Type B   3
   Type X   21 ...etc

}

class invoice {
   int invoicenumber;
   int customernumber;
   List<lineitem> lines;

   struct lineitem {
      string rowtype;
      string somethingelse;
      int whatever;
   }
   public invoice {
      lines = new List<lineitem>;
   }
}

像這樣嗎

inv.SelectMany(i => i.lines).GroupBy(l => l.rowtype).ToDictionary(g => g.Key, g => g.Count())

您可能為此使用了一些LINQ,但是出於簡單性和可讀性的考慮,我建議使用for循環

// Keep a dictionary for count
var lineItemDict = new Dictionary<string, int>();
foreach (var inv in invoices)
{
    foreach (var line in inv.lines)
    {
        // If the rowtype already exists, increment the count
        if (lineItemDict.ContainsKey(line.rowtype))
        {
            lineItemDict.TryGetValue(line.rowtype, out count);
            lineItemDict[line.rowtype] = count + 1;
        }
        else
        {
            // Else add a new entry
            lineItemDict.Add(line.rowtype, 1);
        } 
    }
}

使用LINQ:

// Keep a dictionary for count
var lineItemDict = new Dictionary<string, int>();
invoices.ForEach(inv => {
    inv.lines.ForEach(line => {
        // If the rowtype already exists, increment the count
        if (lineItemDict.ContainsKey(line.rowtype))
        {
            lineItemDict.TryGetValue(line.rowtype, out count);
            lineItemDict[line.rowtype] = count + 1;
        }
        else
        {
            // Else add a new entry
            lineItemDict.Add(line.rowtype, 1);
        }

    });
});

這兩個都將為您提供一個字典( lineItemDict ),看起來像這樣:

<rowtype> : <count>

例如,

'A' : 34
'B' : 3
'X' : 21

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM