Guillaume Paris
Guillaume Paris

Reputation: 10539

linq select new and string

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

namespace ConsoleApplication1
{ 
    class TestIO
    {  
        static void Main()
        {
            string line = "first-main-in-c#";

            var stringQuery = from ch in line where Char.IsDigit(ch) select new string(ch + '-');

            foreach (var c in stringQuery)
                Console.Write(c); 
            Console.WriteLine(System.Environment.NewLine + "Press any key to exit");

            Console.ReadKey();  
        }
    }
}

I am beginner in c# , what is my mistake, I expected this output:

f-i-r-s-t-m-a-i-n-i-n-c

but i get :

System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Char,<>f__Anonymou
sType0`1[System.Int32]] 

Upvotes: 0

Views: 6906

Answers (3)

driis
driis

Reputation: 164291

Char.IsDigit determines whether the character is a decimal digit. There are no decimal digit characters in that string. You could use Char.IsLetter or Char.IsLetterOrDigit, depending on you want to include digits or not.

You are also calling a constructor on string that does not exist. You could use the one that takes a char array.

Finally, the query will return a sequence of strings. To get the desired result (one string as you stated), the code taking the above into account, could be:

string line = "first-main-in-c#";
var stringQuery = from ch in line where Char.IsLetter(ch) select new string(new char[] {ch, '-'});
string result = String.Join("", stringQuery);

This however will include a - at the end you will need to trim off. String.Join joins strings with a separator, so to get the result you want, this could be simpler:

string line = "first-main-in-c#";
var result = String.Join("-", from ch in line where Char.IsLetter(ch) select ch.ToString());

Upvotes: 4

M.Ob
M.Ob

Reputation: 1837

You can use the following:

var stringQuery = from ch in line where Char.IsLetter(ch) select ch + "-";

You will still need to trim off the last "-" to get the exact output you want.

I hope this helps

Upvotes: 0

Servy
Servy

Reputation: 203834

The easiest way to convert a character to a string is to use ToString on the character.

There is no overload of the string constructor that takes just one character, or a string.

You could use any of the following:

char c = 'a';

string s = c.ToString();
s = new string(c, 1);
s = new string(new[] { c });
s = c + "";

Since you adding two characters together you already have a string, so there's no need for new string in the first place:

var stringQuery = from ch in line
                  where Char.IsDigit(ch) 
                  select ch + '-';

Upvotes: 3

Related Questions