我想把自己的头放在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>;
}
}
答案 0 :(得分:2)
像这样吗?
inv.SelectMany(i => i.lines).GroupBy(l => l.rowtype).ToDictionary(g => g.Key, g => g.Count())
答案 1 :(得分:0)
您可能为此使用一些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