0

I'm just learning expression bodied members for class properties, and the basics are easy enough, but I'm trying to determine if the following getter could even be written as an expression bodied member - not for performance gain or anything, simply as a learning exercise:

public static List<Block> AllBlocks
{
    get
    {
        List<Block> allBlocks = new List<Block>(goalBlocks.Count +
                                pathBlocks.Count +
                                boardBlocks.Count);
        allBlocks.AddRange(goalBlocks);
        allBlocks.AddRange(pathBlocks);
        allBlocks.AddRange(boardBlocks);

        return allBlocks;
    }
}

As far as I can tell it cannot because it declares a new variable. I've tried several ways of writing it like other FBM properties, and even went out on a limb and tried writing it in similar styles to a Parallel.For and Parallel.ForEach loop which I didn't expect to work, but figured I'd give it a try.

Jesse Williams
  • 653
  • 7
  • 21
  • 1
    Well you could use `new[] { goalBlocks, pathBlocks, boardBlocks}.SelectMany(x => x).ToList()` which would achieve the same result, but slightly less efficiently... – Jon Skeet Aug 17 '21 at 11:03
  • There's a data dependency, so don't use any parallel processing. It will only add unnecessary overhead. – JHBonarius Aug 17 '21 at 11:17
  • @JHBonarius - thanks. I'm not actually using parallel processing, was just explaining one of the styles I was attempting to mimic for the `getter`. – Jesse Williams Aug 17 '21 at 11:34

1 Answers1

4

You could move away from declaring a new list inside your getter and rewrite as a simple union expression:

public static List<Block> AllBlocks =>
  goalBlocks.Union(pathBlocks).Union(boardBlocks).ToList();

Or if you don't explicitly need a list:

public static IEnumerable<Block> AllBlocks =>
  goalBlocks.Union(pathBlocks).Union(boardBlocks);

As pointed out below, .Union() will remove duplicates. If you don't intend for this to happen then you could use .Concat() instead.

public static IEnumerable<Block> AllBlocks =>
  goalBlocks.Concat(pathBlocks).Concat(boardBlocks);
Chris Pickford
  • 8,642
  • 5
  • 42
  • 73
  • 1
    I would use `Concat`... But the question is if he/she/they can or want to use Linq at all.. – JHBonarius Aug 17 '21 at 11:16
  • 1
    I think you meant to use `.Concat`. `Union` will remove duplicates, so would not be equivalent to the example. – JonasH Aug 17 '21 at 11:16