[英]Counting and accessing items in a list of lists ie: invoice with line items
I am trying to wrap my head around C# Lists, coming from a strong PHP background and thinking of things in PHP Array terms, but I have a class that includes a list and I am trying to count distint items within it. 我试图围绕C#列表,这来自强大的PHP背景并以PHP Array术语来思考,但是我有一个包含列表的类,并且试图计算其中的不连续项。 Is there a simple linq way to do this or would I use some sort of nested foreach?
有没有简单的linq方法可以做到这一点,还是我会使用某种嵌套的foreach?
Thank you in advance 先感谢您
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())
You could probably use some LINQ for this, however for the sake of simplicity and readability, I would recommend using for loops 您可能为此使用了一些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);
}
}
}
With LINQ: 使用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);
}
});
});
Both of these will leave you with a dictionary ( lineItemDict
) that looks like this: 这两个都将为您提供一个字典(
lineItemDict
),看起来像这样:
<rowtype> : <count>
For example, 例如,
'A' : 34
'B' : 3
'X' : 21
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.