yet another LINQ question

Hi, LINQ is hard .....

My entire test application is below

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace ConsoleApplication3
{
    class Program
    {
        private Single getAverageX(List<PointF> points)
        {
            Single average = (from point in points 
                                select point.X
                              ).Average();

            return average;
        }


        public void TestLinq()
        {
            List<PointF> points = new List<PointF> { new PointF(1f, 2f), new PointF(3f, 4f) };
            Console.WriteLine(getAverageX(points));
            points = new List<PointF> { new PointF(1f, 2f) };
            Console.WriteLine(getAverageX(points));
            points = new List<PointF>();
            Console.WriteLine(getAverageX(points));
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            p.TestLinq();
        }
    }
}

Open in new window


It almost works !

The first time getAverageX is invoked, it calculates the average of 1 and 3 and returns 2. Correct.
The second time getAverageX is invoked, it calculates the average of 1 and no other numbers and returns 1. Correct.
The third time getAverageX is invoked, it errors. I need to provide a default value of 0 to get it to work.

LINQ has this FirstOrDefault method that I think I need to use. But I can't quite get there. I know this is simple, I really do, I just can't get there.

Thank you again experts for reading my third post in 3 days.
John BolterAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Randy PooleCommented:
It is working correct, you keep recreating the List.  You need to add another element like:
points.Add( new PointF(1f, 2f));
instead of
points = new List<PointF> { new PointF(1f, 2f) };
0
Randy PooleCommented:
and the 3rd time it will error since you have no entries so a dived by zero
0
käµfm³d 👽Commented:
It's not a divide by zero, it's an InvalidOperationException, and you receive it because the Average method does not work across an empty sequence (e.g. List). You must have at least one element in the sequence before calling Average.

One approach:

private Single getAverageX(List<PointF> points)
{
    if (points.Count == 0)
    {
        return 0;
    }

    Single average = (from point in points
                        select point.X
                        ).Average();

    return average;
}

Open in new window

0
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

John BolterAuthor Commented:
Thanks everyone, so the FirstOrDefault method cannot somehow be used to provide a value of 0 when there are no items in the list?
0
Randy PooleCommented:
as kaufmed showed, use that to provide a return when no ittems exist.
0
käµfm³d 👽Commented:
IMO, FirstOrDefault doesn't make sense here. With that method you are saying, "Give me the first element in the list, unless the list is empty, then give the default value for the type the list contains." I think you would be better served by DefaultIfEmpty:

e.g.

private Single getAverageX(List<PointF> points)
{
    Single average = (from point in points
                        select point.X
                        ).DefaultIfEmpty().Average();

    return average;
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
John BolterAuthor Commented:
Thanks

The following code does not compile, but it does use FirstOrDefault how I think it could be used.

        private Single getAverageX(List<PointF> points)
        {
            Single average = (from point in points 
                                select point.X
                              ).FirstOrDefault(0f).Average();

            return average;
        }

Open in new window


So how is FirstOrDefault used here rather than having the extra if statement?

I hope this makes sense.

Thank you

John B
0
John BolterAuthor Commented:
Yes, DefaultIfEmpty is what I was after. Thank you, I was close, but I had been close to sorting this for 3 hours!
0
John BolterAuthor Commented:
Thank you!!
0
Randy PooleCommented:
lol, ok kind of missed me answering first part of this question? :P
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.