Expression bodied member equivalent

194 views Asked by At

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.

1

There are 1 answers

2
Chris Pickford On

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