How can I control the loop of Tuple repetition?
Someone has given me a hint about an algorithm, which I have modified a little.
int LimCol = Convert.ToInt32(LimitColis);
result = oListTUP
.GroupBy(x => x.Item1)
.Select(g => new
{
Key = g.Key,
Sum = g.Sum(x => x.Item2),
Poids = g.Sum(x => x.Item3),
})
.Select(p => new
{
Key = p.Key,
Items = Enumerable.Repeat(LimCol , p.Sum / LimCol).Concat(Enumerable.Repeat(p.Sum % LimCol, 1)),
CalculPoids = p.Poids / (Enumerable.Repeat(LimCol, p.Sum / LimCol).Concat(Enumerable.Repeat(p.Sum % LimCol, 1))).Count()
})
.SelectMany(p => p.Items.Select(i => Tuple.Create(p.Key, i, p.CalculPoids)))
.ToList();
foreach (var oItem in result)
{
Label1.Text += oItem.Item1 + "--" + oItem.Item2 + "--" + oItem.Item3 + "<br>";
}
the result with LimCol = 3

As you can see, I colored the problem with red.
PS: I have created some Tuple for not using data from SQL
var list = new List<Tuple<string, int, decimal>>
{
Tuple.Create("0452632", 12, 15.0m),
Tuple.Create("essai 49", 1, 45.0m),
Tuple.Create("essai 49", 1, 45.0m),
Tuple.Create("essai 49", 2, 45.0m),
Tuple.Create("essai 49", 1, 23.0m),
};
int TheLimCol = 3;
var Theresult = list
.GroupBy(x => x.Item1)
.Select(g => new
{
Key = g.Key,
Sum = g.Sum(x => x.Item2),
Poids = g.Sum(x => x.Item3),
})
.Select(p => new
{
Key = p.Key,
Items = Enumerable.Repeat(TheLimCol, p.Sum / TheLimCol).Concat(Enumerable.Repeat(p.Sum % TheLimCol, 1)),
CalculPoids = p.Poids / (Enumerable.Repeat(TheLimCol, p.Sum / TheLimCol).Concat(Enumerable.Repeat(p.Sum % TheLimCol, 1))).Count()
})
.SelectMany(p => p.Items.Select(i => Tuple.Create(p.Key, i, p.CalculPoids)))
.ToList();
foreach (var oItem in Theresult)
{
Label1.Text += oItem.Item1 + "--" + oItem.Item2 + "--" + oItem.Item3 + "<br>";
}
Actual output:
0452632--3--3,0
0452632--3--3,0
0452632--3--3,0
0452632--3--3,0
0452632--0--3,0
essai 49--3--79,0
essai 49--2--79,0
expected result:
0452632--3--3,75
0452632--3--3,75
0452632--3--3,75
0452632--3--3,75
essai 49--3--79,00
essai 49--2--79,00
The problem is in your “.Concat(Enumerable.Repeat(p.Sum % TheLimCol, 1)”. You’re adding an element even if the remainder (p.Sum % TheLimCol) is equal to 0.
This should work:
In this specific case, I would recommend using the alternative syntax of Linq (or not using Linq at all):