C#总结列表列表中的值

时间:2021-06-27 11:00:34

标签: c# linq sum

是否可以仅使用 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();

4 个答案:

答案 0 :(得分:4)

使用 SelectMany 将有助于将序列展平为一个序列:

var totalSum= listOfLists.SelectMany(x => x).Sum();

答案 1 :(得分:1)

没有测试过,但我认为你可以写:

double sum = listOfLists.Select(innerList=>innerList.Sum()).Sum();

Select 方法将返回一个包含所有子列表总和的 IEnumerable,然后将其相加。

(我是用手机写的,代码有问题请见谅)

答案 2 :(得分:1)

试试这个

        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();

答案 3 :(得分:1)

你可以使用 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);
    }
}
相关问题