Ehrlich gesagt habe ich etwas gebraucht um den Titel richtig zu wählen. Aber ich möchte einmal aufzeigen, welches Szenario ich meine:
Man hat eine Collection mit folgenden Datumelementen:
31.12.2014 |
01.01.2015 |
02.01.2015 |
16.02.2015 |
19.02.2015 |
20.02.2015 |
|
und möchte sie so sortieren:
Von – Bis
31.12.2014 |
02.01.2015 |
16.02.2015 |
16.02.2015 |
19.02.2015 |
20.02.2015 |
|
|
Als Quelle steht uns eine gefüllte List zur Verfügung:
|
List<Tuple<double, DateTime>> myCollection |
Das heißt, wenn der nächste Eintrag nicht der darauffolgende Tag ist, wird eine neue Gruppe erstellt.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
var groups = new List<List<DateTime>>(); var group1 = new List<DateTime>() { myCollection[0].Item2 }; groups.Add(group1); DateTime lastDate = myCollection[0].Item2; for (int i = 1; i < myCollection.Count; i++) { DateTime currDate = myCollection[i].Item2; TimeSpan timeDiff = currDate - lastDate; bool isNewGroup = timeDiff.Days > 1; if (isNewGroup) { groups.Add(new List<DateTime>()); } groups.Last().Add(currDate); lastDate = currDate; } } |
Möchte man nun noch die von und bis Werte auswerten, kann man folgendes nutzen:
|
int count = 0; //summiere Werte und schreibe pro Gruppe eine neue Zeile foreach (var group in groups) { double value = 0; for (int i = 0; i < group.Count; i++) { value += myCollection[count].Item1; count++; } Von = group[0]; Bis = group[group.Count - 1]; countBuchungen ++; } |
Quelle: http://stackoverflow.com/questions/27393626/in-c-what-is-the-best-way-to-group-consecutive-dates-in-a-list
Login