• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

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.
0
John Bolter
Asked:
John Bolter
  • 4
  • 4
  • 2
1 Solution
 
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 4
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now