-1

I have an Entity Framerwork API controller that returns a list of objects called 'systems'.

In that object, I have an ICollection property called StarSystems that is a collection of ints that represent string names.

Instead of returning the array of ints, I'd like to return the actual names that those ints represent.

So instead of StarSystems looking like this:

[1, 2, 3] or [1, 3] etc... 

it would look like this

["Alpha Zeta III", "Omega System X", "Cygnus X-1"] or ["Alpha Zeta III", "Cygnus X-1"] etc...

So I tried doing this so that it returns the desired string based on the int, but it is giving me this error:

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();  

Is there a way to do this?

Thanks!

SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185

1 Answers1

1

You would need a view model class where the StarSystems property is an enumerable of strings rather than ints, and then project into that. You can't just covert to strings and then stuff that back into the same int collection.

Assuming the actual property type is an enumerable of string, then the code you have should work as-is. However, it would probably make more sense to use an enum, rather than just a flat int, so you don't need ternaries on top of ternaries. Short of that, you can also just use a switch expression:

StarSystems = x.StarSystems switch
{
    1 => "Alpha Zeta III",
    2 => "Omega System X",
    3 => "Cygnus X-1",
    _ => throw new InvalidOperationException("Invalid star system id.")
}
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • Hi - I actually tried an enum but I couldn't get the names to work because they have spaces and I also couldn't figure out how to compare them inline inside the Linq query. – SkyeBoniwell Apr 15 '20 at 15:02
  • 1
    You can use the `Display` attribute on the enum members to give them a more descriptive name, and then get that value as the string value: https://stackoverflow.com/questions/13099834/how-to-get-the-display-name-attribute-of-an-enum-member-via-mvc-razor-code – Chris Pratt Apr 15 '20 at 15:10
  • haha I see so you as if "1 => EnumHelper.GetDisplayValue(1)" etc :) – SkyeBoniwell Apr 15 '20 at 15:18
  • 1
    Yeah. Depending on your needs, you might also consider enumeration classes as well, which give you greater inherent freedom over the string value: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types – Chris Pratt Apr 15 '20 at 15:23