C# 总结列表列表中的值
C# Sum up values in Lists of List
是否可以仅使用 linq 对 List 列表中的所有值求和?
我有有效的代码,但也许 LINQ 有一个不需要 foreach 循环的方法
double totalSum = 0;
Guid key = ((KeyValuePair<Guid, string>)ComboBoxUsers.SelectedItem).Key;
var listOfLists = process._statistics.Where(a => a.UserID == key).Select(p => p.KgIntoBucket);
foreach(List <double> kg in listOfLists)
{
totalSum += kg.Sum();
}
lblKgToBucket.Text = totalSum.ToString();
使用SelectMany,这将有助于将序列展平为一个序列:
var totalSum= listOfLists.SelectMany(x => x).Sum();
没测试过,不过我觉得你可以这样写:
double sum = listOfLists.Select(innerList=>innerList.Sum()).Sum();
Select
方法将 return 一个 IEnumerable
与所有子列表相加,然后再对其求和。
(我用 phone 写的,如果代码中有问题,请见谅)
试试这个
List<List<double>> lstDouble = new List<List<double>>();
List<double> items1 = new List<double>() { 1.231, 4.561, 10.891 };
List<double> items2 = new List<double>() { 1.232, 4.562, 20.892 };
List<double> items3 = new List<double>() { 1.233, 4.563, 7.893 };
List<double> items4 = new List<double>() { 1.234, 30.564, 7.894 };
List<double> items5 = new List<double>() { 40.235, 4.565, 7.895 };
lstDouble.Add(items1);
lstDouble.Add(items2);
lstDouble.Add(items3);
lstDouble.Add(items4);
lstDouble.Add(items5);
var sum = lstDouble.SelectMany(x => x).Sum();
你可以使用 linq 的 AsQueryable() 来做到这一点!
public class Program
{
public static void Main()
{
double totalSum = 0;
List<int> list = new List<int> { 99, 34, 77, 75, 87,77, 35, 88};
var listOfLists = list.Where(a => a == 77).ToList();
int res = listOfLists.AsQueryable().Sum();
Console.WriteLine(res);
}
}
是否可以仅使用 linq 对 List 列表中的所有值求和?
我有有效的代码,但也许 LINQ 有一个不需要 foreach 循环的方法
double totalSum = 0;
Guid key = ((KeyValuePair<Guid, string>)ComboBoxUsers.SelectedItem).Key;
var listOfLists = process._statistics.Where(a => a.UserID == key).Select(p => p.KgIntoBucket);
foreach(List <double> kg in listOfLists)
{
totalSum += kg.Sum();
}
lblKgToBucket.Text = totalSum.ToString();
使用SelectMany,这将有助于将序列展平为一个序列:
var totalSum= listOfLists.SelectMany(x => x).Sum();
没测试过,不过我觉得你可以这样写:
double sum = listOfLists.Select(innerList=>innerList.Sum()).Sum();
Select
方法将 return 一个 IEnumerable
与所有子列表相加,然后再对其求和。
(我用 phone 写的,如果代码中有问题,请见谅)
试试这个
List<List<double>> lstDouble = new List<List<double>>();
List<double> items1 = new List<double>() { 1.231, 4.561, 10.891 };
List<double> items2 = new List<double>() { 1.232, 4.562, 20.892 };
List<double> items3 = new List<double>() { 1.233, 4.563, 7.893 };
List<double> items4 = new List<double>() { 1.234, 30.564, 7.894 };
List<double> items5 = new List<double>() { 40.235, 4.565, 7.895 };
lstDouble.Add(items1);
lstDouble.Add(items2);
lstDouble.Add(items3);
lstDouble.Add(items4);
lstDouble.Add(items5);
var sum = lstDouble.SelectMany(x => x).Sum();
你可以使用 linq 的 AsQueryable() 来做到这一点!
public class Program
{
public static void Main()
{
double totalSum = 0;
List<int> list = new List<int> { 99, 34, 77, 75, 87,77, 35, 88};
var listOfLists = list.Where(a => a == 77).ToList();
int res = listOfLists.AsQueryable().Sum();
Console.WriteLine(res);
}
}