Reputation: 610
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#?
Upvotes: 5
Views: 3493
Reputation: 31636
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()
});
Upvotes: 0
Reputation: 236238
csv.Split(',').Select(s => (Events)Enum.Parse(typeof(Events), s));
BTW with generic enum class you can parse this way Enum<Events>.Parse(s)
and whole code will look like:
csv.Split(',').Select(Enum<Events>.Parse)
Upvotes: 16
Reputation: 753
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));
}
Upvotes: 0
Reputation: 22794
csv.Split(',').Select(x => (Events)int.Parse(x)).ToList();
Upvotes: 1