#TECH

Usage of Into and Let Keyword in Query Expression C#

Problem Statement:

For the below array I want to print all words having length more than 2 after removing letter  “O”.

var numbers = new[] { “ONE”, “TWO”, “THREE”, “FOUR” }.AsQueryable();

Intended output should be:

Result

5EnumerableQuery<String> (2 items)4

THREE

FUR

Without using into and let keyword I have two options.

1) I  tried following query which did not give me correct result as I am checking length prior to replacing the character from select.

var incorrectQuery = (from   number in numbers

                      where   number.Length > 2

                      orderby number

                      select  number.Replace(“O”, “”)).ToList();

Incorrecrt result

5EnumerableQuery<String> (4 items)4

FUR

NE

THREE

TW

2) The other option gave me correct result but I had to write two queries as below.

var correctQuery = from   number in numbers

                   select number.Replace(“O”, “”); 

var correctResult = (from number in correctQuery where number.Length > 2 select number).ToList();

Correct result with two queries

5EnumerableQuery<String> (2 items)4

THREE

FUR

3) But using into I can achieve the result in single query. The into keyword allows creating a temporary variable to store the results.

var usingIntoKeyword = (from n in numbers

                       select n.Replace(“O”, “”)

                       into wordswithnoO

                       where wordswithnoO.Length > 2

                       select wordswithnoO

                ).ToList();

Using into Keyword in single query

5EnumerableQuery<String> (2 items)4

THREE

FUR

Extending my requirement to get the original word along with replaced word to get the intended output as below, I can not use into as it hides the previous variable when used in query.

Original word along with replaced word

5EnumerableQuery<> (2 items)4

number

wordswithnoO

THREE

THREE

FOUR

FUR

Thanks to the let keyword which doesn’t hide the previous variable and creates a new variable.  Below query will yield the desired result.

var usingletKeyword = (

                        from number in numbers

                        let wordswithnoO= number.Replace(“O”, “”)

                        where wordswithnoO.Length > 2

                        select new {number,wordswithnoO}

                        ).ToList();

                          

Please let me know your thought or any other way to do this.

You might also like