Ho un controller API Entity Framerwork che restituisce un elenco di oggetti chiamati "sistemi".
In quell'oggetto, ho una proprietà ICollection chiamata StarSystems che è una raccolta di ints che rappresentano nomi di stringhe.
Invece di restituire la matrice di ints, mi piacerebbe restituire i nomi reali che questi ints rappresentano.
Quindi invece di StarSystems si presenta così:
[1, 2, 3] or [1, 3] etc...
sembrerebbe così
["Alpha Zeta III", "Omega System X", "Cygnus X-1"] or ["Alpha Zeta III", "Cygnus X-1"] etc...
Quindi ho provato a farlo in modo che restituisca la stringa desiderata in base all'int, ma mi sta dando questo errore:
Operator '==' cannot be applied to operands of type 'ICollection<StarSystems>' and 'int'
var systems = await _context.System
.Select(x => new SystemEntity
{
Id = x.Id,
StarSystems = (x.StarSystems == 1) ? "Alpha Zeta III" : (x.StarSystems == 2) ? "Omega System X" : (x.StarSystems == 3) ? "Cygnus X-1",
Title = x.Title,
.ToListAsync();
C'è un modo per fare questo?
Grazie!
Avresti bisogno di una classe del modello di vista in cui la proprietà StarSystems
è un StarSystems
di stringhe piuttosto che ints, e quindi proiettare in quella. Non puoi semplicemente convertire le stringhe e poi reinserirle nella stessa raccolta int.
Supponendo che il tipo di proprietà effettivo sia un elenco di stringhe, il codice in uso dovrebbe funzionare così com'è. Tuttavia, probabilmente avrebbe più senso usare un enum, piuttosto che un semplice int, quindi non hai bisogno di ternari sopra i ternari. A parte questo, puoi anche usare solo un'espressione switch:
StarSystems = x.StarSystems switch
{
1 => "Alpha Zeta III",
2 => "Omega System X",
3 => "Cygnus X-1",
_ => throw new InvalidOperationException("Invalid star system id.")
}