Skip to content

Commit 150d0a7

Browse files
committed
CountAggregator: add optional field to count non-null values of the concrete field #14
1 parent e66f3e8 commit 150d0a7

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

src/NReco.PivotData/CountAggregator.cs

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,17 +22,32 @@ namespace NReco.PivotData {
2222
public class CountAggregator : IAggregator {
2323

2424
ulong count = 0;
25+
string field = null;
2526

2627
public CountAggregator() {
2728
}
2829

30+
public CountAggregator(string field) {
31+
this.field = field;
32+
}
33+
2934
public CountAggregator(object state) {
3035
if (state==null)
31-
throw new InvalidOperationException("Invalid state, expected: uint");
36+
throw new InvalidOperationException("Invalid state, expected: UInt64");
3237
count = Convert.ToUInt64(state);
3338
}
3439

40+
public CountAggregator(string field, object state) : this(state) {
41+
this.field = field;
42+
}
43+
44+
3545
public void Push(object r, Func<object,string,object> getValue) {
46+
if (field!=null) {
47+
var v = getValue(r, field);
48+
if (v == null || DBNull.Value.Equals(v))
49+
return;
50+
}
3651
count++;
3752
}
3853

@@ -61,26 +76,36 @@ public object GetState() {
6176
/// </summary>
6277
public class CountAggregatorFactory : IAggregatorFactory {
6378

79+
public string Field { get; private set; }
80+
6481
public CountAggregatorFactory() {
82+
Field = null;
83+
}
84+
85+
public CountAggregatorFactory(string field) {
86+
Field = field;
6587
}
6688

6789
public IAggregator Create() {
68-
return new CountAggregator();
90+
return new CountAggregator(Field);
6991
}
7092

7193
public IAggregator Create(object state) {
72-
return new CountAggregator(state);
94+
return new CountAggregator(Field, state);
7395
}
7496

7597
public override bool Equals(object obj) {
7698
var aggrFactory = obj as CountAggregatorFactory;
7799
if (aggrFactory==null)
78100
return false;
79-
return true;
101+
return aggrFactory.Field==Field;
80102
}
81103

82104
public override string ToString() {
83-
return "Count";
105+
var s = "Count";
106+
if (Field!=null)
107+
s += " of "+Field;
108+
return s;
84109
}
85110

86111
}

0 commit comments

Comments
 (0)