6

I have a list of strings in C#, and want to create a list of unique characters that are in the strings in the list, using LINQ.

I have so far worked out how to turn the List into a List, but I can't work out how to get the LINQ to go further than that.

What I have so far is as follows:

List<string> dictionary = new List<string>(someArray);
List<string[]> uniqueCharacters = dictionary.ConvertAll(s => s.Split());

I believe I need to something along the lines of

List<char> uniqueCharacters =
     dictionary.ConvertAll(s => s.Split()).SelectAll(t, i=>t[i][0]);
ahsteele
  • 26,243
  • 28
  • 134
  • 248
simonalexander2005
  • 4,338
  • 4
  • 48
  • 92

2 Answers2

16

You can use LINQ's SelectMany method, e.g.:

var list = new List<string> { "Foo", "Bar" };

var chars = list.SelectMany(s => s.ToCharArray());
var distinct = chars.Distinct();
Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
  • List uniqueCharacters = dictionary.SelectMany(s => s.ToCharArray()).Distinct().ToList(); is what I went with in the end - thanks :) – simonalexander2005 Jul 02 '10 at 08:02
  • Using a `HashSet` at the end `var distinct = new HashSet(chars)` is another reasonable alternative if the question is interpreted more liberally. See also http://stackoverflow.com/questions/1388361/getting-all-unique-items-in-a-c-list – Ian Mercer Jul 02 '10 at 08:08
  • The `ToCharArray` call is unnecessary and has a small impact on performance because the characters need to be copied from the source string to a new array. You can just do `list.SelectMany(s => s)` instead. – LukeH Jul 02 '10 at 09:05
1

Get your LinQ result and put it in loop, compare every char with in list of char.

foreach (string character in dictionary)
        {
            if (!(uniqueCharacters).Contains(character))
            {
                uniqueCharacters.Add(character);
            }
        }
Serkan Hekimoglu
  • 4,234
  • 5
  • 40
  • 64