Click here to Skip to main content
Click here to Skip to main content

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

, 14 Feb 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

BenScharbach
Software Developer (Senior) Image-Nexus, LLC
United States United States
No Biography provided

Comments and Discussions

 
SuggestionA more compact method of getting the comma-delimited list of selected items PinmemberJohn Brett18-Feb-14 21:48 
QuestionGood Article PinmemberEvgeny Surikov17-Feb-14 8:07 
QuestionNice! PinprofessionalVolynsky Alex15-Feb-14 6:00 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411019.1 | Last Updated 14 Feb 2014
Article Copyright 2014 by BenScharbach
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid