だから私は列挙型を持っています:
public enum myEnum
{
IBM = 1,
HP = 2,
Lenovo = 3
}
Brand
クラスがあります
public class Brand
{
public Brand(string name, int id)
{
Name = name;
Id = id;
}
public string Name { get; private set; }
public int Id { get; private set; }
}
Brand
からのデータが取り込まれたオブジェクトのリストを作成したいと考えていますMyEnum
。何かのようなもの:
private IEnumerable<Brand> brands = new List<Brand>
{
new Brand(myEnum.IBM.ToString(), (int) myEnum.IBM),
new Brand(myEnum.HP.ToString(), (int) myEnum.HP),
new Brand(myEnum.Lenovo.ToString(), (int) myEnum.Lenovo),
};
2 つの配列を作成できます。1 つは列挙型の名前を持ち、もう 1 つは列挙型の ID を持ち、それらを foreach して反復ごとに Brand オブジェクトを作成しますが、より良い解決策があるかどうか疑問に思います。
最後に、Royi Mindel ソリューションを使用します。Daniel Hilgarth の回答と、Royi Mindel の提案を機能させる手助けをしてくれたことに感謝します。できれば、この質問に対して両方の功績を認めたいと思います。
public static class EnumHelper
{
public static IEnumerable<ValueName> GetItems<TEnum>()
where TEnum : struct, IConvertible, IComparable, IFormattable
{
if (!typeof(TEnum).IsEnum)
throw new ArgumentException("TEnum must be an Enumeration type");
var res = from e in Enum.GetValues(typeof(TEnum)).Cast<TEnum>()
select new ValueName() { Id = Convert.ToInt32(e), Name = e.ToString() };
return res;
}
}
public struct ValueName
{
public int Id { get; set; }
public string Name { get; set; }
}