Alex Grossi
Alex Grossi

Reputation: 11

Can't convert a char to string using standard Linq methods?

I am trying to count the amounts of brackets in a given text using Linq standard methods. This is the code I have written so far.

using System;
using System.Linq;

namespace Exercises
{
    class BracketExercise
    {
        static void Main(string[] args)
        {
            string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
            string value = "(";
            //string value2 = ")";
            
            bool result = bracketlist.Contains(value);
            Console.WriteLine($"Does string contain specified substring? {result}");
            if (result == true)
            {
                int freq = bracketlist.Count(f => (f == value));
                Console.WriteLine(freq);
            }
        }

    }

}

Am I missing something? This piece gives me compiler error CS0019, Operator 'operator' cannot be applied to operands of type 'char' and 'string'. I tried changing "Value" to a var type, but that didn't work either.ch

Upvotes: 0

Views: 380

Answers (5)

Prateek
Prateek

Reputation: 145

You don't need to check the existence of the characters in the string by using Contains method. The count will give you valid result EVEN if there are no instances of the character you are searching. PF the simplest implementation.

string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
char charToFind = '(';
int bCount = bracketList.Count(x => x == charToFind);

Remember, string is a character array.

Upvotes: 0

Caius Jard
Caius Jard

Reputation: 74605

Flater's answer addresses your main complaint, but I did want to discuss this some:

I tried changing "Value" to a var type

There isn't a var type; var is you saying "compiler is allowed to decide the type". The compiler will then look at the type on the right hand side of the = and make a decision based on that

On the right hand side you have "(" - this is a string; nothing makes it not a string so you'll end up in exactly the same place whether you write string value or var value

By now you know you could have written:

var v = '(';

That v would be a char, because '(' is a char;

Other things would also result in chars:

var v = "("[0];

That's a string being indexed by an int, which is an operation that results in a char. In this case, the compiler would also infer a char type for v. That's not to say you'd do that - it's just to demo that v ends up as what the compiler determines the final outcoming type of the right hand operation is


Typically we aim to use var when it's obvious what the type is on the other side, or if it's something horrific, like the output of a LINQ query that includes other data and has a where clause etc, and we don't want type out IIncludableQueryableSomethingThatsReallyLongAndDoesntMatter v = ...

There are times when you should avoid using var if it makes the code harder to read:

//method name is poor; doesn't make it obvious what it does, or returns
//variable name is poor too; we'll have to rely on intellisense lots here
var v = DoProcess();

There are also times where you should avoid using var because it makes life hard work. Looping over old collections that don't implement IEnumerable<T> is a good example:

foreach(var row in someDataTable.Rows)

row here will end up typed as object, which is a nuisance to use. THis happens because .Rows is a DataRowCollection and the enumerator for it claims it returns an object - it's actually a DataRow but it's wrapped up inside an object. foreach will do a cast for you if you don't use var:

foreach(DataRow row in someDataTable.Rows)

And this is cleaner than var'ing it and having to cast:

foreach(var row in someDataTable.Rows.Cast<DataRow>())
  ..

//or
foreach(var row in someDataTable.Rows){
  var actualRow = (DataRow)row;
  ..
}

Upvotes: 0

Pawan Lakhara
Pawan Lakhara

Reputation: 1150

Try following code.

string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
Char value = '('; // replace string char
bool result = bracketlist.Contains(value);
Console.WriteLine($"Does string contain specified substring? {result}");
if (result == true)
   {
      int freq = bracketlist.Count(f => (f == value));
      Console.WriteLine(freq);
    }

Upvotes: 0

Flater
Flater

Reputation: 13773

When using LINQ, a string is treated like it's an IEnumerable<char> This means that in the following code:

int freq = bracketlist.Count(f => (f == value));

f is of type char, not string. Since value is of type string, your code is trying to do char == string, which is the source of the error.

In this case, I would suggest you change your value to also be a char:

char value = '(';

Take note of the different ' quotes. "A" is a string, 'A' is a char. The quotes you use are important to the compiler.

Upvotes: 3

PMF
PMF

Reputation: 17185

On the line int freq = bracketlist.Count(f => (f == value)); f is of type char (because the enumeration on a string works on char). You are comparing it to value, which is of type string. Change string value = "("; to char value = '(';. Note the single quotes used to declare a char (as opposed to using double quotes, which declares a string).

Upvotes: 0

Related Questions