Is linq's let keyword better than its into keyword?

前端 未结 4 1927
鱼传尺愫
鱼传尺愫 2020-12-22 22:09

I\'m currently brushing up on LINQ and am trying to comprehend the difference between the let and using the into keyword. So far the let

4条回答
  •  轮回少年
    2020-12-22 22:49

    Yes, because they're doing different things, as you've said.

    select ... into effectively isolates the whole of one query and lets you use it as the input to a new query. Personally I usually prefer to do this via two variables:

    var tmp = from n in names
              select Regex.Replace(n, "[aeiou]", "");
    
    var noVowels = from noVowel in tmp
                   where noVowel.Length > 2
                   select noVowel;
    

    (Admittedly in this case I would do it with dot notation in two lines, but ignoring that...)

    Often you don't want the whole baggage of the earlier part of the query - which is when you use select ... into or split the query in two as per the above example. Not only does that mean the earlier parts of the query can't be used when they shouldn't be, it simplifies what's going on - and of course it means there's potentially less copying going on at each step.

    On the other hand, when you do want to keep the rest of the context, let makes more sense.

提交回复
热议问题