2

I have a LinkedList<Point> which I'm trying to apply a lambda to:

LinkedList<Point> node = LinkedPoints.Where<Point>(x => x.X + x.Y / someValue % 2 == 0);

..where LinkedPoints is a LinkedList<Point>. I want to create a new LinkedList<Point> from the original where the coordinates of the Point added together and divided by some value results in an even number. The actual condition of the lambda isn't important because currently the code above does not work, and I'd like to know why and how I can make it work.

I think that this lambda is operating on Point and so it'll return List<Point> however I want a new LinkedList<Point> - how can I achieve this?

trainreq
  • 381
  • 4
  • 12
  • 2
    `x.X + x.Y / someValue % 2` I strongly suggest adding `(` and `)` to make that calculation easier to read. – mjwills Oct 22 '19 at 02:54
  • The actual condition I'm using is `x.X / nudDivisor.Value + x.Y / nudDivisor.Value % 2 == 0` - how would you split this up to be readable? – trainreq Oct 22 '19 at 03:07

1 Answers1

4

Just use the constructor of LinkedList that accepts an IEnumerable parameter:

LinkedList<Point> node =
    new LinkedList<Point>(LinkedPoints.Where(x => x.X + x.Y / someValue % 2 == 0));

You can also create an extension method similar to the .ToList() and .ToArray() methods:

static class EnumerableExtensions
{
    public static LinkedList<T> ToLinkedList<T>(this IEnumerable<T> collection)
    {
        return new LinkedList<T>(collection);
    }
}

Usage:

LinkedList<Point> node = 
    LinkedPoints.Where(x => x.X + x.Y / someValue % 2 == 0).ToLinkedList();

Notes:

  • .Where<Point> can be simplified to just .Where because the type is inferred from the list.
  • As mjwills indicated in the comments, it's highly recommended to use parenthesis in your condition to make the calculation logic clearer and to avoid mistakes. See Arithmetic operators precedence and associativity for reference. Also, beware not to fall victim for unintended Integer Division.