Search code examples
c#linqclonevalue-typereference-type

Best way to shallow copy a list of objects containing an enum


public enum Settings
{
   MySettingOne,
   MySettingTwo
}

public class MySettings
{
    public Settings Setting { get; set; }
}

public List<MySettings> SettingsConfig = new List<MySettings>();
SettingsConfig.Add(new MySettings() { Setting = Settings.MySettingOne });
SettingsConfig.Add(new MySettings() { Setting = Settings.MySettingTwo });

Ok lets say i have the above setup. I want to create a copy of SettingsConfig. Since the enum is a value type i wont need to work about the reference of this but only of MySettings.

For the sake of argument i dont have access to the code to implement a MemberwiseClone on MySettings.

Im thinking this can be done with linq but im not seeing it.


Solution

  • How about projecting each item into new MySettings?

    var copy = SettingsConfig
               .Select(x => new MySettings() 
                            { 
                               Setting = x.Setting
                            }).ToList();