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,865 other followers

Archive for November 21st, 2012

.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);

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);

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:
                    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: Read the rest of this entry »

Posted in .NET, .NET 3.5, .NET 4.5, C#, C# 3.0, C# 4.0, C# 5.0, Development, LINQ, Software Development, Visual Studio 11, Visual Studio 2008, Visual Studio 2010, Visual Studio and tools | 2 Comments »

%d bloggers like this: