4 回答
TA贡献1951条经验 获得超3个赞
编辑解决方案,因为您进行了编辑。
String[][] TValue = new String[][]
{
new String[] {"1.11", "2.11", "3.11" },
new String[] {"2.11", "3.11", "4.11" },
new String[] {"4.11", "5.11", "6.11" }
};
Console.WriteLine("Avg[0] => {0:F2}", TValue.Select(x => double.Parse(x[0])).Average());
Console.WriteLine("Avg[1] => {0:F2}", TValue.Select(x => double.Parse(x[1])).Average());
Console.WriteLine("Avg[2] => {0:F2}", TValue.Select(x => double.Parse(x[2])).Average());
这是你所期望的。
希望这项工作。
TA贡献1155条经验 获得超0个赞
看来你需要avg基于列索引而不是行然后.Zip将是你的一个选择,
假设您的字符串列表列表是,
var myList = new List<List<string>>
{
new List<string> { "1.11, 2.11, 3.11" }, //<= Notice here single item in list with comma(,) separated
new List<string> { "2.11, 3.11, 4.11" },
new List<string> { "4.11, 5.11, 6.11" }
};
因此,您需要首先使用逗号 ( ,) 将内部列表中的字符串拆分,以将每个项目作为单独的字符串,
var list = myList
.SelectMany(x => x
.Select(y => y.Split(',')
.Select(z => z.Trim())
.ToList()))
.ToList();
然后你可以.Zip通过
var results = list[0]
.Zip(list[1], (a, b) => double.Parse(a) + double.Parse(b))
.Zip(list[2], (x, y) => (x + double.Parse(y)) / 3)
.ToList();
//------------------Print the result---------------
foreach (var item in results)
{
Console.WriteLine(Math.Round(item, 2));
}
如何.Zip运作?
让我们获取索引 0 上的所有列值。
a = "1.11"
b = "2.11"
那么第一个Zip结果将是=>
double.Parse(a) + double.Parse(b)
= 1.11 + 2.11
= 3.22
所以对于第二个.Zip,x现在是上面第一个的结果,.Zip这意味着
x = 3.22
y = "4.11"
那么第二个Zip结果将是=>
(x + double.Parse(y)) / 3
= (3.22 + 4.11) / 3
= 2.44
因此,Average对于您在列索引 0 => 处的值2.44
在上面,
list[0]:字符串列表中的第一个列表。
list[1]:字符串列表中的第二个列表。
list[2]:字符串列表中的第三个列表。
输出:(来自控制台)
TA贡献1815条经验 获得超6个赞
您可以压缩所有三个列表
using System;
using System.Collections.Generic;
using System.Linq;
public static class MyFunkyExtensions
{
public static IEnumerable<TResult> ZipThree<T1, T2, T3, TResult>(
this IEnumerable<T1> source,
IEnumerable<T2> second,
IEnumerable<T3> third,
Func<T1, T2, T3, TResult> func)
{
using (var e1 = source.GetEnumerator())
using (var e2 = second.GetEnumerator())
using (var e3 = third.GetEnumerator())
{
while (e1.MoveNext() && e2.MoveNext() && e3.MoveNext())
yield return func(e1.Current, e2.Current, e3.Current);
}
}
}
class MainClass {
public static void Main (string[] args) {
var list = new List<List<double>> { new List<double> {1.11,2.11,3.11}, new List<double> {2.11,3.11,4.11}, new List<double> {4.11,5.11,6.11} };
var a = list[0].ZipThree(list[1], list[2], (x, y, z) => (x + y + z) / 3);
Console.WriteLine(
string.Join(",",
a.Select(s => s.ToString())));
}
}
它返回
2.44333, 3.443333, 4.44333
TA贡献1818条经验 获得超7个赞
我假设所有内部列表都具有相同的长度,并且您想计算相应索引的平均值(即 index0 是每个列表中第 0 个值的平均值,index1 是第 1 个值的平均值等)。
在这种情况下,要获得每个索引的平均值,您可以使用以下代码:
int listLength = myList.First().Length; // Length for an array
// Count for a List<T>
var averages = Enumerable.Range(0, listLength).Select(
index => myList.Average(innerList => double.Parse(innerList[index]))
).ToList();
- 4 回答
- 0 关注
- 86 浏览
添加回答
举报