Elegiac
Elegiac

Reputation: 366

Cannot implicit convert type 'System.Collections.Generic.IEnumerable<char>'to'string

I'm wondering what's wrong with my code:

var trimmed = RemoveFromStart(Slb, new String[]{ "ab", "Ac", "Accep", "Acces", "Accessible", "AccessibleE" });

var uniqueItems = trimmed.Distinct();

rtb.SelectedText = uniqueItems;

Error pointing "uniqueItems".

//Replacing Parameter:
        public string RemoveFromStart(string s, IEnumerable<string> strings)
        {
        foreach (var x in strings.Where(s.StartsWith))
        {
            return s.Remove(0, x.Length);
        }
         return s;
        }

I just want every strings to be unique like "Accep" will still exist even "Ac" was the shortest string.

How can I do that?

Upvotes: 1

Views: 5555

Answers (5)

Tim Schmelter
Tim Schmelter

Reputation: 460158

An IEnumerable<Char> is not a string, so if you need one you can use the constructor:

rtb.SelectedText = new String(uniqueItems.ToArray());

If you want to find the first matching string in your abbreviation-list:

var abbreviations = new String[] { "ab", "Ac", "Accep", "Acces", "Accessible", "AccessibleE" };
string abbr = abbreviations.FirstOrDefault(a => Slb.StartsWith(a));
rtb.SelectedText = abbr ?? Slb;

Upvotes: 3

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

Since Enumerable.Distinct() method returnsIEnumerable<T> (in this case IEnumerable<Char>) which is not clearly a string, you can use it with char[] constructor to initialize it.

rtb.SelectedText = new String(uniqueItems.ToArray());

Initializes a new instance of the String class to the value indicated by an array of Unicode characters.

Upvotes: 1

V4Vendetta
V4Vendetta

Reputation: 38210

Did you check what Distinct returns in this case its IEnumerable<char> so you will have to convert the same to a string using the constructor overloads of char[]

so you can do a new string(trimmed.Distinct().ToArray()) and assign it to SelectedText which is expecting a string

Upvotes: 1

Daniel Imms
Daniel Imms

Reputation: 50189

You're returning a string and using Distinct() to get the unique characters, this returns as an IEnumerable<char>. Tou need to convert it back into a string somehow, here is one method:

rtb.SelectedText = string.Join(string.Empty, uniqueItems);

Upvotes: 0

fhnaseer
fhnaseer

Reputation: 7277

You need to convert it to string. It will not convert automatically.

var uniqueItems = trimmed.Distinct();
rtb.SelectedText = new string(uniqueItems);

Upvotes: 0

Related Questions