Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / C# 5.0
Tip/Trick

How-To Convert a String Collection to a Multi-Enum Item Using TryParse

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
14 Feb 2014CPOL3 min read 19.7K   6   3
How-To Convert a String Collection to a Multi-Enum item using TryParse

Introduction

In this tip, I am going to talk about how I was able to convert a list of string values, which represents a list of enum values, and convert them to a single enum (flags) item using a single .NET built-in call, which you might not be familiar with. Also, I will show you how I got the correct symbol to use for the .NET parser, which was not shown in the intelli-sense documentation and discuss the .NET cool file/directory listener called ‘FileSystemWatcher’.

Background

You should have some familiarity with the .NET framework and C# coding language. Also, if you would like a talking demo of this topic, please see my YouTube video: http://youtu.be/pIFetREWb24.

Using the Code

In my project, I am creating a WCF service which will listen to some root folder location and notify my application of any file activity. In .NET, there is a class called ‘FileSystemWatcher’, which allows you to create a listener which will trigger events for given actions; like, ‘Create’ and ‘Delete’. In this ‘FileSystemWatcher’ class, you can set a property called ‘NotifyFiltersenum. This ‘NotiftyFiltersenum allows for several enum settings, using the symbol ‘|’ to separate each enum action. For example, to set the three actions of ‘LastAccess’, ‘LastWrite’ and ‘FileName’, I wrote the following code:

C#
// Note: The 'NotifyFilters.DirectoryName' will not trigger when some Filter is set.
FileSystemWatcherService = new FileSystemWatcher();
FileSystemWatcherService.Filter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName; 

Take note of the ‘|’ symbol used to concatenate these 3 different enumeration actions. In .NET, when you decorate any Enum with the ‘[Flags]’ attribute, it allows the item to hold multiple values, rather than one enum setting. This symbol is what you use when setting the ‘NotifyFiltersenum with multiple items.

In my front-end application, I want the user to be able to select these ‘Enum’ values from some given WPF ListBox. The ListBox will hold a list of ‘String’ values, which will be populated using the following code:

C#
// Set collection on combobox for NotifyFilters.
var notifyFilters = Enum.GetNames(typeof (NotifyFilters));
lstNotifyFilters.ItemsSource = notifyFilters;

The important thing to notice in the code above is the use of the .NET Enum static class. It has several cool features, which allows for Enum manipulation. In my code above, I used the ‘GetNames()’ method call, which will return a collection of string values for any Enum type. This collection is then set to the ListBox using the ‘ItemSource’ property. The ListBox is then set to allow for ‘Multiple’ selections, allowing the user to select several Enum actions for the ‘NotifyFiltersenum. The problem now is how do I convert these string values back to a single Enum type of ‘NotifyFilters’?

The solution is simple, since .NET has another method called ‘TryParse’ built into the static Enum class. However, when you first examine the signature of the ‘TryParse’ call, you will notice it only accepts one ‘String’ item in the first param, and not multiple. At first glance, you might make the assumption that this ‘TryParse’ call will not create an Enum with the ‘[Flags] type. But in fact, if you dig down into the ‘TryParse’ code in .NET, you will find that it does handle multiple words in the first parameter using a comma symbol splitter. With this in mind, I decided to iterate the original selected items collection from the ListBox and then build a single string output with each selection separated with the comma symbol. My final method looks like the following:

C#
/// <summary> 
/// Occurs when the user clicks the 'Set' button for the NotifyFilter type. 
/// </summary>
private void btnSetNotifyFilter_Click(object sender, RoutedEventArgs e) 
{
     // get collection of items selected from listbox
     var itemsSelected = lstNotifyFilters.SelectedItems;
     var notifyFiltersStringBuilder = new StringBuilder(); 

    // iterate collection and 
     var count = itemsSelected.Count;
     for (var index = 0; index < count; index++)
     {
         // Get current item
         var itemSelected = itemsSelected[index].ToString();

         // Append to stringBuilder  
        notifyFiltersStringBuilder.Append(itemSelected);

         // Check if not the last item. 
        if (index < count - 1)
            notifyFiltersStringBuilder.Append(","); // Note:DO NOT USE | symbol, must be a comma. - Ben
      }

      // build Enum using TryParse - then, send to WCF service. 
     NotifyFilters notifyFilters;

      if (Enum.TryParse(notifyFiltersStringBuilder.ToString(), out notifyFilters)) 
      {
         SetNotifyFiltersType(null, notifyFilters);
      }
 }

Points of Interest

I was able to learn not to stop at just the ‘TryParse’ signature and assume it could only handle one string item, but with some .NET code digging, I discovered you can have it parse multiple string words from one string by using the comma delimiter.

History

  • Initial Version – 2/14/2014 – Ben Scharbach

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Image-Nexus
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionA more compact method of getting the comma-delimited list of selected items Pin
John Brett18-Feb-14 20:48
John Brett18-Feb-14 20:48 
QuestionGood Article Pin
Evgeny Surikov17-Feb-14 7:07
Evgeny Surikov17-Feb-14 7:07 
QuestionNice! Pin
Volynsky Alex15-Feb-14 5:00
professionalVolynsky Alex15-Feb-14 5:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.