Search code examples
c#distinct

Distinct() returning char rather than element


I am trying to figure out why Distinct() works here:

 string[] words= new string[] {"Cupcake","Cake","Candy", "Candy"};

      var uniqueWords = 
         from word in words
         orderby word
         select word; 

      foreach (var word in uniqueWords.Distinct())
      {
         Console.Write($" {word}");

But not here:

        var uniqueWords = from c in array
                          orderby c
                          select c.Distinct();

        foreach (var element in uniqueWords) 
                Console.WriteLine($"{element}");

I get the System.Linq.Enumerable+DistinctIterator`1[System.Char] console output

I have tried casting result but no success.


Solution

  • This is because your select here is select c.Distinct() as in select all the distinct characters from the string c:

    var uniqueWords = from c in array
                          orderby c
                          select c.Distinct();
    

    So if for example your item is "Cupcake" the distinct of this is an array of char:

    'C','u','p','c','a','k','e'

    You need to do:

    (from c in array orderby c select c).Distinct()