C# 计算具有相同项目计数的多个IEnumerable的平均值
假设我们有多个相同项目计数的C# 计算具有相同项目计数的多个IEnumerable的平均值,c#,linq,average,ienumerable,C#,Linq,Average,Ienumerable,假设我们有多个相同项目计数的IEnumerables var multipleEnumerables = new[] { new[] { 10, 20, 30 } new[] { 11, 21, 31 } new[] { 12, 22, 32 } new[] { 13, 23, 33 } } 如何获得使用LINQ的平均值,从而产生以下结果: new[] { 11.5, 21.5, 31.5 } 枚举数可能会有所不同(即不固定为四个) 每个枚举表中的项目数可能不
IEnumerable
s
var multipleEnumerables = new[]
{
new[] { 10, 20, 30 }
new[] { 11, 21, 31 }
new[] { 12, 22, 32 }
new[] { 13, 23, 33 }
}
如何获得使用LINQ的平均值,从而产生以下结果:
new[] { 11.5, 21.5, 31.5 }
枚举数可能会有所不同(即不固定为四个)
每个枚举表中的项目数可能不同(即不固定为三个),但对于该特定实例的所有枚举表,项目数将相同。更新以响应编辑 如果您有
IEnumerable
,您可以使用如下内容:
IEnumerable<IEnumerable<Test>> multipleEnumerables = new[] {
new [] { new Test { Value = 10 }, new Test { Value = 20 } },
new [] { new Test { Value = 11 }, new Test { Value = 21 } }
};
var averages = multipleEnumerables
.SelectMany(e => e.Select((v, i) => new { Index = i, Item = v }))
.GroupBy(e => e.Index)
.Select(e => e.Select(v => v.Item.Value).Average())
.ToArray();
由于您对压缩两个以上的
IEnumerable
感兴趣,这里有一个扩展方法(ZipAll
),它演示了如何将多个IEnumerable
压缩在一起。实际上,这会旋转数据,使列变成行
public static class ZipEx
{
public static IEnumerable<IEnumerable<T>> ZipAll<T>(
this IEnumerable<IEnumerable<T>> src)
{
return src
.Aggregate(
(IEnumerable<IEnumerable<T>>)null,
(acc, curr) => acc == null
? curr.Select(x => x.ToEnumerable())
: acc.Zip(curr, (a, c) => a.Append(c)));
}
public static IEnumerable<T> ToEnumerable<T>(this T item)
{
yield return item;
}
}
谢谢你,约翰!我想我把问题简单化了
Zip
与两个IEnumerable
s一起工作,但是如果有两个以上(因此是多个)怎么办?基本上我有一个IEnumerable
。你介意我更新我的问题吗?天才!我可能花了几天的时间才弄明白非常感谢你!
public static class ZipEx
{
public static IEnumerable<IEnumerable<T>> ZipAll<T>(
this IEnumerable<IEnumerable<T>> src)
{
return src
.Aggregate(
(IEnumerable<IEnumerable<T>>)null,
(acc, curr) => acc == null
? curr.Select(x => x.ToEnumerable())
: acc.Zip(curr, (a, c) => a.Append(c)));
}
public static IEnumerable<T> ToEnumerable<T>(this T item)
{
yield return item;
}
}
var averages = multipleEnumerables.ZipAll().Select(x => x.Average()); //.ToArray()