2

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?

DanDan
  • 1,038
  • 4
  • 15
  • 28
  • 2
    it returns `IEnumerable` because a string is a collection of chars – derloopkat Nov 07 '18 at 22:08
  • Take a look at: https://stackoverflow.com/questions/958949/difference-between-select-and-selectmany. In particular, search for "list 'Fruits' contains 'apple'" in one of the answers – Flydog57 Nov 07 '18 at 22:11

1 Answers1

5

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.

Marco
  • 56,740
  • 14
  • 129
  • 152