Adwad ddw
Adwad ddw

Reputation: 11

C# Iterate through string with Linq .Select()

Why can't I iterate through a string and add the letters (chars) to a HashSet like in the example above.

I tried to execute this part of the code but the HashSet was empty. `

HashSet<char> chars2 = new HashSet<char>();
myString.Select(l => chars2.Add(l));

`

Upvotes: 0

Views: 453

Answers (3)

knittl
knittl

Reputation: 265889

Select is a LINQ method. Most LINQ methods are intermediate expressions and don't consume the collection. You must call a terminal operation such as ToList or ForEach to actually "execute" the query.

But note that using Select/ForEach to add to a set is a bit odd: you are using a functional approach to execute a side-effect (inherently non-functional!).

Instead, use the extension method ToHashSet() directly if available in your .NET version:

HashSet<char> chars2 = myString.ToHashSet();

Upvotes: 1

gunr2171
gunr2171

Reputation: 17579

I'm not sure what the "example above" is, but you're using LINQ incorrectly. The Select method should not be used to create side effects. chars2.Add() creates a side effect.

In addition, most Linq methods are not executed if they don't need to be. This is called "Deferred Execution".

Instead, use a foreach, which is intended to create side effects while looping through elements.

var myString = "abcd";
HashSet<char> chars2 = new HashSet<char>();

foreach (var chr in myString)
{
    chars2.Add(chr);
}

There are also more direct ways to create a hash set from specifically a string

myString.ToHashSet()
new HashSet<char>(myString)

Upvotes: 1

Arcturus
Arcturus

Reputation: 27065

Delayed/deferred execution! There is no need to evaluate the Select

If you add a ToList() to the end, it will execute your lambda and will add the items.

You can also change it to a ForEach

Knowing this, beware that if you do not a ToList() to it, and iterate your collection, it will execute it again and again, so if your Select is expensive to run, make sure to run it once.

Upvotes: 1

Related Questions