Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi, I thought I understood LINQ according to my book. I don't.

All I want to do is sum some numbers. My code is below. The bit that doesn't compile is obvious.
My question is what am I doing wrong? All I want to do is sum the numbers 1 + 2 + 5 - 1000 + 100 = -892 but I can't even do that.

Please please can someone help me out here.

Thank you

XML
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication7
{
    class C3
    {
        public C3(int foo) { Foo = foo; }
        public int Foo { get; set; }
    }

    class C2
    {
        public C2(List<C3> bar) { Bar = bar; }
        public List<C3> Bar { get; set; }
    }

    class C1
    {
        public C1(List<C2> baz) { Baz = baz; }
        public List<C2> Baz { get; set; }
    }


    class Program
    {
        public void Run()
        {
            C2 c2_1 = new C2(new List<C3> {new C3(1), new C3(2), new C3(5)});
            C2 c2_2 = new C2(new List<C3> { new C3(-1000), new C3(100) });

            C1 c1 = new C1(new List<C2>() { c2_1, c2_2 });

            //Answer = -892, but I can't even get the syntax right for it to compile
            var resultSum = c1.Baz.Select(x => x.Bar).Sum(y => y.Foo);

        }
        static void Main(String[] args)
        {
            new Program().Run();
        }
    }
}
Posted
Comments
BillWoodruff 18-Feb-14 9:51am    
I'd suggest you start with less complex and esoteric examples, and then "work upwards" toward the more complex uses.

I think Baz.Select returns a list of lists, nl. a list of Bar (which is a list) ant the lsit does not have property Foo
Have you tried SelectMany ?
 
Share this answer
 
Hi Serge, yes I tried SelectMany too, code below:

C#
var resultSum = c1.Baz.Select(x => x.Bar).SelectMany(y => y.Foo).Sum(z => z);


I cant get this to compile either so although I think the syntax is correct, it clearly is not.
 
Share this answer
 
you can do it like that:
C#
var resultSum = c1.Baz.SelectMany(x => // selecting all Bars as one IEnumerable
    x.Bar).Sum(x => // summing all Foos.
        x.Foo);


ps: please send your comment as comment, not a solution.
 
Share this answer
 
Comments
Jon Joeney 17-Feb-14 7:23am    
Sorry Vedat, I'm pretty new to this forum and programming and I didn't see the Comment option. Thank you
Vedat Ozan Oner 17-Feb-14 7:29am    
you are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900