Home > front end >  how to find the number of specific enum members in c#?
how to find the number of specific enum members in c#?

Time:01-13

I have an object that can come in various sizes.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum Size
{
    Small = 0,
    Medium,
    Large
}

public class BallSizes : MonoBehaviour
{
    [SerializeField] private Size size;
}

After assigning the Size to various objects. I want to see how many objects are Small or Large etc.

Enum.GetName() and Enum.GetValue() seems to only return the names/values of the objects, instead of the total amount of objects that are of that type.

CodePudding user response:

if you have a bunch of objects with different sizes, and want to count the number of each size, you could for example use LINQ

var counts = myObjects.GroupBy(obj => obj.Size).Select(group => (group.Key, group.Count());

CodePudding user response:

I don't quite understand what you want to do @lovelyladder, but try with reflection if you want to retrieve the name and value of the enum.

foreach(var x in sizeObj.GetType().GetEnumNames())
{
    Console.WriteLine(x);
}
foreach(var x in sizeObj.GetType().GetEnumValues())
{
    Console.WriteLine(x);
}
  • Related