0

I have an array of enums that I need to convert to an anonymous object with a property for each enum.

For example:

public enum MyColors
{
    Red,
    Blue,
    Green,
}

What I need is

new { MyColors.Red, MyColors.Blue}

I have a List

var colorList = new List<MyColors> {MyColors.Red, MyColors.Blue};

There a shorthand way of creating an anonymous object with every element in my list as a property?

Not looking for ExpandoObject

FizzBuzz
  • 683
  • 3
  • 8
  • 1
    Not really, but why do you need an anonymous object of enums? – TheGeneral Aug 09 '19 at 02:46
  • Can you describe the desired behaviour of this anonymous object? Do you mean you want an `obj` where `obj.Red` evaluates to `MyColors.Red` and `obj.Blue` evaluates to `MyColors.Blue`? Why not just use `MyColors` then? – Sweeper Aug 09 '19 at 02:47
  • Think the closest you get is something like `new { Red = MyColors.Red, Blue = MyColors.Blue }` – Tieson T. Aug 09 '19 at 02:47
  • If you need an actual array of the values, there's always [Enum.GetValues](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=netframework-4.8) – Tieson T. Aug 09 '19 at 02:48
  • Anonymous objects need to be compiled. Their fields cant be created dynamically like this, the *runtime* would not know what to do with them, also you wouldn't be able to write code to use the properties – TheGeneral Aug 09 '19 at 02:54
  • I need an anonymous object to use with a diff library that's expecting it.... I only want certain enums available (Red & Blue) and I wanted to reuse some existing logic returning the filtered list above... – FizzBuzz Aug 09 '19 at 02:58
  • `new { MyColors.Red, MyColors.Blue}` – TheGeneral Aug 09 '19 at 02:58
  • Enum.GetValues won't work - 1. I'm not looking for an array of values. 2. I only want certain values of the Enum – FizzBuzz Aug 09 '19 at 02:58
  • @TheGeneral - yeah, that's what I have now - I was just looking for a neater way to reuse some existing logic that's returning the list of colors I want as a list – FizzBuzz Aug 09 '19 at 02:59
  • please elaborate what diff library does and how it uses this object? is this something related to serialization? You can construct types in the runtime using [Emit](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit?view=netframework-4.8) but this will not be a 'shorthand' :) – fenixil Aug 09 '19 at 03:38
  • maybe you are looking for ExpandoObject. – iSR5 Aug 09 '19 at 05:06
  • perhaps that would work. Thank you. Definitely not a duplicate with the ExpandoObject question that Peter Dunhio pasted.... but I guess he finds pleasure in marking questions as dupes – FizzBuzz Aug 09 '19 at 13:50

0 Answers0