C# Linq 按键组合多个序列
我有两个需要合并的 IList
。
Traffic 是一个简单的类:
class Traffic
{
long MegaBits;
DateTime Time;
}
每个 IList
拥有相同的时间,我需要一个 IList
,我在其中总结了兆位,但将时间保留为钥匙。
使用 Linq 可以吗?
编辑:
我忘了提及,时间在任何列表中不一定是唯一的,多个 Traffic
实例可能具有相同的时间。
另外,我可能会遇到 X 个列表(超过 2 个),我也应该提到这一点 - 抱歉 :-(
示例:
IEnumerable<IList<Traffic>> trafficFromDifferentNics;
var combinedTraffic = trafficFromDifferentNics
.SelectMany(list => list)
.GroupBy(traffic => traffic.Time)
.Select(grp => new Traffic { Time = grp.Key, MegaBits = grp.Sum(tmp => tmp.MegaBits) });
上面的示例有效,所以感谢您的输入 :-)
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 => new Traffic { Time = grp.Key, MegaBits = grp.Sum(tmp => tmp.MegaBits) });
The example above works, so thanks for your inputs :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这听起来更像是
或者,经过你的返工
this sounds more like
or, with your rework
您可以将两个列表中的项目组合成一个集合,然后对键进行分组以获得总和,然后再转换回一组新的
Traffic
实例。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.这听起来像:
请注意,这将以成对的方式加入,因此如果每个列表中有多个具有相同时间的元素,您可能无法获得您想要的结果。
That sounds like:
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.