Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq take first item from list, cast error

Tags:

c#

casting

linq

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

like image 347
JulyAnn Jackson Avatar asked Sep 02 '25 17:09

JulyAnn Jackson


2 Answers

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

like image 97
Ghassen Avatar answered Sep 05 '25 07:09

Ghassen


you don't need to unboxing you can use:

_settings.Take(1)

if you want to convert different type:

_settings.Take<yourAwesomeType>(1);

like image 34
Yunus Kıran Avatar answered Sep 05 '25 06:09

Yunus Kıran