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

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

3 Comments

List<char> uniqueCharacters = dictionary.SelectMany(s => s.ToCharArray()).Distinct().ToList(); is what I went with in the end - thanks :)
Using a HashSet at the end var distinct = new HashSet(chars) is another reasonable alternative if the question is interpreted more liberally. See also stackoverflow.com/questions/1388361/…
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.
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);
            }
        }

2 Comments

Good answer, but I was hoping to be able to do it all in LinQ - for the learning experience, if nothing else
Its just like an Sql command DISTINCT write your LinQ Query, and add Distinct() at last

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.