简体   繁体   中英

How to convert CSV string to List<Enum>

I have defined enum events:

public enum Events {
  UNLOCK = 1,
  LOCK = 2
}

as well as CSV string:

var csv = "1,2";

What would be preferable way to convert csv string to List< Events> in C#?

csv.Split(',').Select(s => (Events)Enum.Parse(typeof(Events), s));

BTW与通用枚举类,您可以解析这种方式Enum<Events>.Parse(s)和整个代码将如下所示:

csv.Split(',').Select(Enum<Events>.Parse)
csv.Split(',').Select(x => (Events)int.Parse(x)).ToList();

A more verbose way:

    var csv = "2,1,1,2,2,1";

    List<Events> EventList = new List<Events>();

    foreach (string s in csv.Split(','))
    {
        EventList.Add((Events)Enum.Parse( typeof(Events), s, true));
    }

If your whole CSV line is not just events, use regex to parse out the line into its components. Here we have a mixed CSV line and regex can break out each of the values using named match captures. From there we parse it using linq into a new projection for each line of data found.

var csvLine = "1245,1,2,StackOverFlow";
var pattern = @"
^                          # Start at the beginning of each line.
(?<IDasInteger>[^,]+)      # First one is an ID
(?:,)                      # Match but don't capture the comma
((?<Events>[^,]+)(?:,)){2} # 2 Events
(?<Summary>[^\r\n]+)       # Summary text";

var resultParsed = Regex.Matches(csvLine, pattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline)
                        .OfType<Match>()
                        .Select (mt => new {

                        ID = int.Parse (mt.Groups["IDasInteger"].ToString()),
                        Event = mt.Groups["Events"].Captures
                                                   .OfType<Capture>()
                                                   .Select (cp => (Events)Enum.Parse(typeof(Events),  cp.Value))),
                        Summary = mt.Groups["Summary"].ToString()
                  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM