joe smhoe
joe smhoe

Reputation: 1

How do you add the sum of lists when the sublist is int?

How do you add the sum of List of List when the sub list is int. I know you can't do mainList.Sum(); because you can't add a list data type so I have to use loops and another list to get around it. If I don't want to use loops is there a simpler way of doing it ?

var mainList = new List<List<int>>( );
mainList.Add(new List<int>{ 6});
mainList [0].Add (5);
mainList [0].Add (3);
mainList.Add(new List<int>{ 7});
mainList [1].Add (5);
mainList [1].Add (2);
mainList.Add(new List<int>{ 8});
mainList [2].Add (5);
mainList [2].Add (19);

without having to do this..

List<int> list = new List<int>();
for (int i =0; i <3; i++)
{
    for (int j = 0; j <mainList[i].Count; j++) 
    {
        list.Add (mainList [i] [j]);
    }
}
Console.Write (list.Sum ()); 

Upvotes: 0

Views: 66

Answers (2)

Slai
Slai

Reputation: 22876

Or sum the sums:

int sum = mainList.Sum(x => x.Sum());

Upvotes: 1

Jonesopolis
Jonesopolis

Reputation: 25370

LINQ's SelectMany will flatten the object to one collection, then you can just call Sum() on it:

var result = mainList.SelectMany(i => i).Sum();
//result = 60

Upvotes: 5

Related Questions