Skip to content

KAJAN M.

moon indicating dark mode
sun indicating light mode

Creating a static list from another static list with additional items in C#

March 14, 2021

Recently I came across a way to create a new static list based on another static list with some additional items in a single statement. Since the initialization is done in a static class, we can’t just create the list in one statement and add items later as we do normally.

So, the idea is to combine constructor initialization with object initialization syntax. Below is a code example for your reference.

using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace StaticList
{
public static class OfficerStatuses
{
public enum OfficerStatus
{
Pending,
Accepted,
DeploymentCommenced,
Resigned,
Blacklisted
}
public static readonly ReadOnlyCollection<OfficerStatus> InactiveOfficerStatuses = new List<OfficerStatus>
{
OfficerStatus.DeploymentCommenced,
OfficerStatus.Resigned,
OfficerStatus.Blacklisted
}.AsReadOnly();
public static readonly ReadOnlyCollection<OfficerStatus> OfficerStatusesToHide =
new List<OfficerStatus>(InactiveOfficerStatuses)
{
OfficerStatus.Pending
}.AsReadOnly();
}
}

Creating a new list(array) from another one with additional entries in a single call is dead simple in JavaScript. Well, now we know that is the case in C# as well πŸ˜‰


πŸ‘‹ Hi! Welcome to my blog. I'm Kajan, a full-stack engineer focusing on JavaScript(Vue, React) and ASP.NET Core stack. I am thankful to the internet community for helping me out on various occasions πŸ™πŸ˜˜. I hope to give back to the community by sharing my experience, and knowledge.