Concise C# code for gathering several properties with a non-null value into a collection?
- by stakx
A fairly basic problem for a change. Given a class such as this:
public class X
{
public T A;
public T B;
public T C;
...
// (other fields, properties, and methods are not of interest here)
}
I am looking for a concise way to code a method that will return all A, B, C, ... that are not null in an enumerable collection. (Assume that declaring these fields as an array is not an option.)
public IEnumerable<T> GetAllNonNullAs(this X x)
{
// ?
}
The obvious implementation of this method would be:
public IEnumerable<T> GetAllNonNullAs(this X x)
{
var resultSet = new List<T>();
if (x.A != null) resultSet.Add(x.A);
if (x.B != null) resultSet.Add(x.B);
if (x.C != null) resultSet.Add(x.C);
...
return resultSet;
}
What's bothering me here in particular is that the code looks verbose and repetitive, and that I don't know the initial List capacity in advance.
It's my hope that there is a more clever way, probably something involving the ?? operator? Any ideas?