Line by line it should be:
List<Test> testList = new List<Test>();
// string, string, string = Property1, Property2, Property3
var dict = new Dictionary<Tuple<string, string, string>, List<Test>>();
foreach (var el in testList)
{
List<Test> list;
var key = Tuple.Create(el.Property1, el.Property2, el.Property3);
if (!dict.TryGetValue(key, out list))
{
list = new List<Test>();
dict.Add(key, list);
}
list.Add(el);
}
var output = new List<Test>(dict.Count);
foreach (var kv in dict)
{
var list = kv.Value;
var el = new Test
{
Property1 = kv.Key.Item1,
Property2 = kv.Key.Item2,
Property3 = kv.Key.Item3,
Property4 = list[0].Property4,
};
output.Add(el);
for (int i = 0; i < list.Count; i++)
{
el.Property5 += list[i].Property5;
el.Property6 += list[i].Property6;
el.Property7 += list[i].Property7;
el.Property8 += list[i].Property8;
}
}
The only "real" advantage here is that the inner for
cycle for the Sum
part is a single for
instead of being the four separate for
used by the four separate Sum
.
But there is another way to do it, that is different from LINQ...
List<Test> testList = new List<Test>();
// string, string, string = Property1, Property2, Property3
var dict = new Dictionary<Tuple<string, string, string>, Test>();
foreach (var el in testList)
{
Test el2;
var key = Tuple.Create(el.Property1, el.Property2, el.Property3);
if (!dict.TryGetValue(key, out el2))
{
el2 = new Test
{
Property1 = el.Property1,
Property2 = el.Property2,
Property3 = el.Property3,
Property4 = el.Property4,
};
dict.Add(key, el2);
}
el2.Property5 += el.Property5;
el2.Property6 += el.Property6;
el2.Property7 += el.Property7;
el2.Property8 += el.Property8;
}
var output = dict.Values.ToList();
Here we unify the two foreach
cycles and we remove the inner for
cycle.
Now, unless you are working on million of records, I don't think the difference will amount to much for both solutions.
Note that there is an important difference in output between my code and the LINQ code: the GroupBy
operator, when used on a IEnumerable
, guarantees the ordering of the groups to be the same as in the input (so the first element will generate the first group, the next element with a different key will generate the second group and so on). Using a Dictionary<,>
this doesn't happen. The ordering of the output isn't defined and will be "random".