开发者

C# Linq Combine multiple sequences by key

I have two IList<Traffic> I need to combine.

Traffic is a simple class:

class Traffic
{
  long MegaBits;
  DateTime Time;
}

Each IList holds the same Times, and I need a single IList<Traffic>, where I have summed up the MegaBits, but kept the Time as key.

Is this possible using Linq ?

EDIT:

I forgot to mention that Time isn't necessarily unique in any list, multiple Traffic instances may have the same Time.

Also I might run into X lists (more than 2), I should had mentioned that as well - sorry :-(

EXAMPLE:

IEnumerable<IList<Traffic>> trafficFromDifferentNics;

var combinedTraffic = trafficFromDifferentNics
                        .SelectMany(list => list)
                        .GroupBy(traffic => traffic.Time)
                        .Select(grp =>开发者_C百科 new Traffic { Time = grp.Key, MegaBits = grp.Sum(tmp => tmp.MegaBits) });

The example above works, so thanks for your inputs :-)


this sounds more like

var store = firstList.Concat(secondList).Concat(thirdList)/* ... */;
var query = from item in store
            group item by item.Time
            into groupedItems
            select new Traffic
            {
                MegaBits = groupedItems.Sum(groupedItem => groupedItem.MegaBits),
                Time = groupedItems.Key
            };

or, with your rework

IEnumerable<IList<Traffic>> stores;
var query = from store in stores
            from item in store
            group item by item.Time
            into groupedItems
            select new Traffic
            {
                MegaBits = groupedItems.Sum(groupedItem => groupedItem.MegaBits),
                Time = groupedItems.Key
            };


You could combine the items in both lists into a single set, then group on the key to get the sum before transforming back into a new set of Traffic instances.

var result = firstList.Concat(secondList)
    .GroupBy(trf => trf.Time, trf => trf.MegaBits)
    .Select(grp => new Traffic { Time = grp.Key, MegaBits = grp.Sum()});


That sounds like:

var query = from x in firstList
            join y in secondList on x.Time equals y.Time
            select new Traffic { MegaBits = x.MegaBits + y.MegaBits,
                                 Time = x.Time };

Note that this will join in a pair-wise fashion, so if there are multiple elements with the same time in each list, you may not get the results you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜