本文介绍了将字符串数组转换为枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个直接的解决方案,用于将字符串数组转换为枚举

i尝试了很多解决方案,但没有结果

i need a straight solution for converting array of strings to enum
i tried alot of solutions but no result

推荐答案

enum myEnum
    {
    One, Two, Three
    }
private void myButton_Click(object sender, EventArgs e)
    {
    string[] inputs = new string[] { "One", "Two", "Three" };
    myEnum[] outputs = inputs.Select(i => (myEnum) Enum.Parse(typeof(myEnum), i)).ToArray();
    ...


using System;
using System.Linq;

namespace Sample {
    enum Fruits {
        Banana,
        Apple,
        Orange,
        Pineapple
    }

    class Program {
        static void Main(string[] args) {
            var fruitStrings = new[] {"Banana", "Apple", "Pineapple", "Orange"};
            var fruits = fruitStrings.Select(fs => (Fruits)Enum.Parse(typeof (Fruits), fs));
            Console.WriteLine("Strings: {0}", String.Join(", ", fruitStrings));
            Console.WriteLine("Enums  : {0}", String.Join(", ", fruits));
        }
    }
}



希望这会有所帮助,

Fredrik Bornander


Hope this helps,
Fredrik Bornander


public class Problem001
{
    private enum Fruits
    {
        Banana,
        Apple,
        Orange,
        Pineapple
    }

    public Problem001()
    {
        string[] names = Enum.GetNames(typeof(Fruits));
        for (int iIndex = 0; iIndex < names.Length; iIndex++)
        {
            Console.WriteLine(names[iIndex]);
        }
    }
}


这篇关于将字符串数组转换为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:11