Search code examples
c#linq

How to check particular character present in it


Here is my code:

using System;

namespace HelloWorld
{
    class Program
    {  
        static void Main(string[] args)
        {
            string ContactEmail = "[email protected]";
            Console.WriteLine("Hello World!"); 
      
            Console.WriteLine(ContactEmail.Substring(0, ContactEmail.IndexOf('@'))); 
        }
    }
}

Output: pinky.

I want to check whether the string contain @ and is not empty, then only find substring, else return null. Don't need If else block. In same line using : operator


Solution

  • Well, you can find index with a help of IndexOf and then check index for -1 - if @ is not found:

    int index = ContactEmail.IndexOf('@');
    
    // If you don't want "if" let's use ternary operator
    var result = index < 0 ? null : ContactEmail[..index];
    

    If you are looking for Linq you can put something like this:

    // Note, that you'll have empty string, not null here
    var result = string.Concat(ContactEmail.TakeWhile(c => c != '@'));
    
    // If you insist on null
    result = result == "" ? null : result;