The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,118 other followers

.NET/C# LINQ gem: How to check if a char in a list of characters (via Stack Overflow)

Posted by jpluimers on 2012/11/21

Often when comparing characters with a list of characters, that list does not consist of consts.

It if were, you could make a switch statement:

                    switch (item)
                    {
                        case '/':
                        case '\\':
                        case ';':
                            addSeparator(separatorsUsed, item);
                            break;
                    }

But reality is that you cannot do things like this:

                    switch (item)
                    {
                        case Path.AltDirectorySeparatorChar: // Error: A constant value is expected
                        case Path.DirectorySeparatorChar:
                        case Path.PathSeparator:
                            addSeparator(separatorsUsed, item);
                            break;
                    }

However, you can perform a small trick and use LINQ to write some pretty elegant code based on Contains.

                    char[] pathSeparators = { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar, Path.PathSeparator };
                    // LINQ: http://stackoverflow.com/questions/1818611/how-to-check-if-a-char-in-a-char-array/1818635#1818635
                    if (pathSeparators.Contains(item))
                        addSeparator(separatorsUsed, item);

The LINQ logic has the logic backwards (you can think of it like “item in pathSeparators”, but it is far easier to read than this:

                    if ((item == Path.AltDirectorySeparatorChar) || (item == Path.DirectorySeparatorChar) || (item == Path.PathSeparator))
                        addSeparator(separatoseparatorsUsedrsInUse, item);

Full source of a demo application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading.Tasks;

namespace CharIsInSetConsoleApplication
{
    class Program
    {
        /*
         * call with arguments like this:
         *     ftp://besharp.com;C:\Windows\system32\cmd.exe 
         */
        static void Main(string[] args)
        {
            List<char> separatorsUsed = getSeparatorsUsed(args);

            Console.WriteLine("Separators used in args:");
            // regular foreach is more readable, but you can use LINQ here too: 
            // http://stackoverflow.com/questions/823532/apply-function-to-all-elements-of-collection-through-linq/823563#823563
            separatorsUsed.ForEach(item => 
                Console.WriteLine(item)
            );
            Console.Write("Press <Enter>");
            Console.ReadLine();
        }

        private static List<char> getSeparatorsUsed(string[] args)
        {
            char[] pathSeparators = { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar, Path.PathSeparator };
            List<char> separatorsUsed = new List<char>();
            foreach (string arg in args)
            {
                foreach (char item in arg)
                {
                    switch (item)
                    {
                        case '/':
                        case '\\':
                        case ';':
                            addSeparator(separatorsUsed, item);
                            break;
                    }

                    //switch (item)
                    //{
                    //    case Path.AltDirectorySeparatorChar: // Error: A constant value is expected
                    //    case Path.DirectorySeparatorChar:
                    //    case Path.PathSeparator:
                    //        addSeparator(separatorsUsed, item);
                    //        break;
                    //}

                    if ((item == Path.AltDirectorySeparatorChar) || (item == Path.DirectorySeparatorChar) || (item == Path.PathSeparator))
                        addSeparator(separatorsUsed, item);

                    // LINQ: http://stackoverflow.com/questions/1818611/how-to-check-if-a-char-in-a-char-array/1818635#1818635
                    if (pathSeparators.Contains(item))
                        addSeparator(separatorsUsed, item);
                }
            }
            return separatorsUsed;
        }

        private static void addSeparator(List<Char> separatorsUsed, char item)
        {
            if (!separatorsUsed.Contains(item))
                separatorsUsed.Add(item);
        }
    }
}

–jeroen

via: c# – How to check if a char in a char array – Stack Overflow.

2 Responses to “.NET/C# LINQ gem: How to check if a char in a list of characters (via Stack Overflow)”

  1. Paul Hilt said

    Would a regular expression not be more appropriate? At least it is as elegant to read :-)

    • jpluimers said

      Depends on the characters, especially if there is escaping involved.
      Maybe I’ll find some time to compare the two and do some speed comparisons.
      –jeroen

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: