Home > other >  C# Iterate through string with Linq .Select()
C# Iterate through string with Linq .Select()

Time:12-06

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

`

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

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 ToHashSet() directly:

HashSet<char> chars2 = myString.ToHashSet();
  •  Tags:  
  • c#
  • Related