Home > Enterprise >  C# Linq take first item from list, cast error
C# Linq take first item from list, cast error

Time:12-13

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'.

CodePudding user response:

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

CodePudding user response:

you don't need to unboxing you can use:

_settings.Take(1)

if you want to convert different type:

_settings.Take<yourAwesomeType>(1);

CodePudding user response:

Yeah, when you use either .FirstOrDefault(); or .First(); rather than .Take(1); it should work.

  • Related