Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with SelectMany? [duplicate]

Tags:

c#

linq

I've encountered an issue with the SelectMany expression that I just can't wrap my head around.

Consider this: I have a collection of objects of this class

class Tag
{
    string DisplayText { get; set; }
    string Key { get; set; }
    int Value { get; set; }
}

Now I'm trying to get all my display texts (actually part of a much more complex expression):

var texts = AvailableTags.SelectMany(t => t.DisplayText);

Now why does this return me an IEnumerable<char> instead of an IEnumerable<string>??? Am I missing something?

like image 311
DanDan Avatar asked Oct 25 '25 06:10

DanDan


1 Answers

If AvailableTags is a list (an IEnumerable) then you should simply use

var texts = AvailableTags.Select(t => t.DisplayText);

The "strange" result you have using SelectMany is due (exactly as said from @derloopkat) to the fact that a string is a collection of char.
So you can imagine your code like this:

class Tag
{
    List<char> DisplayText { get; set; }
    string Key { get; set; }
    int Value { get; set; }
}

When you use SelectMany you're getting all the chars contained in every DisplayText and then the result is flattened.

like image 167
Marco Avatar answered Oct 26 '25 19:10

Marco