Search code examples
c#linqcasting

C# Linq take first item from list, cast error


private List<Setting> _settings;
private Setting _setting;

_settings = _atlasService.GetSettings();
_setting = (Setting)_settings.Take(1);

I'm trying to set _setting as the first item in the list of _settings (there is only one record in the list)

On the last line of code I am getting this error:

System.InvalidCastException HResult=0x80004002 Message=Unable to cast object of type 'd__25`1[Atlas.Entities.Setting]' to type 'Atlas.Entities.Setting'.


Solution

  • replace the line _setting = (Setting)_settings.Take(1);

    by

    _setting = _settings.First();
    

    the take method returns IEnumerable while you are casting to a just one Setting