c# - Merge elements in list by property -
context
i have list of time intervals. time interval type histomesures
.
each histomesure
defined debut
(begin) property, fin
(end) property, , commentaires
(a little note) property.
my list made in such way :
- all
histomesure
exclusive, mean can't overlapping each other. - the list sorted
debut
, beggining of interval. - edit :
histomesure
contiguous in configuration.
question
i want merge (transform 2 little intervals in 1 big interval) adjacent histomesure
have same commentaires
. achieve way :
//sortedhistos type list<histomesure> int = 0; while (i < sortedhistos.count - 1) { if (sortedhistos[i].commentaires == sortedhistos[i + 1].commentaires) { sortedhistos[i].fin = sortedhistos[i + 1].fin; sortedhistos.removeat(i + 1); } else { ++i; } }
but feel exists more elegant way this, maybe linq. have suggestion ?
using linq , borrowing this article group adjacent values, should work:
your query:
var filteredhistos = sortedhistos .groupadjacent(h => h.commentaires) .select(g => new histomesure { debut = g.first().debut, fin = g.last().fin, commentaires = g.key });
and copying article, rest of code group by:
public class groupofadjacent<tsource, tkey> : ienumerable<tsource>, igrouping<tkey, tsource> { public tkey key { get; set; } private list<tsource> grouplist { get; set; } system.collections.ienumerator system.collections.ienumerable.getenumerator() { return ((system.collections.generic.ienumerable<tsource>)this).getenumerator(); } system.collections.generic.ienumerator<tsource> system.collections.generic.ienumerable<tsource>.getenumerator() { foreach (var s in grouplist) yield return s; } public groupofadjacent(list<tsource> source, tkey key) { grouplist = source; key = key; } } public static class localextensions { public static ienumerable<igrouping<tkey, tsource>> groupadjacent<tsource, tkey>( ienumerable<tsource> source, func<tsource, tkey> keyselector) { tkey last = default(tkey); bool havelast = false; list<tsource> list = new list<tsource>(); foreach (tsource s in source) { tkey k = keyselector(s); if (havelast) { if (!k.equals(last)) { yield return new groupofadjacent<tsource, tkey>(list, last); list = new list<tsource>(); list.add(s); last = k; } else { list.add(s); last = k; } } else { list.add(s); last = k; havelast = true; } } if (havelast) yield return new groupofadjacent<tsource, tkey>(list, last); } }
Comments
Post a Comment