tags:

views:

114

answers:

2

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]);
A: 

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
Good answer, but I was hoping to be able to do it all in LinQ - for the learning experience, if nothing else
simonalexander2005
Its just like an Sql command DISTINCTwrite your LinQ Query, and add Distinct() at last
Serkan Hekimoglu
+12  A: 

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
List<char> uniqueCharacters = dictionary.SelectMany(s => s.ToCharArray()).Distinct().ToList();is what I went with in the end - thanks :)
simonalexander2005
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
Hightechrider
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
awesome, thanks!
simonalexander2005