Concise C# code for gathering several properties with a non-null value into a collection?
Posted
by stakx
on Stack Overflow
See other posts from Stack Overflow
or by stakx
Published on 2010-05-23T21:13:51Z
Indexed on
2010/05/23
21:20 UTC
Read the original article
Hit count: 278
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?
© Stack Overflow or respective owner