Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
14 Feb 2014 1  
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:

// 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:

// 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:

/// <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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here