Common Linq / Standard Query Operator mistakes/mis-steps?

后端 未结 4 1060
感动是毒
感动是毒 2021-01-03 09:30

For programmers that do not come from a functional programming background, are there an mistakes to avoid?

4条回答
  •  -上瘾入骨i
    2021-01-03 10:06

    For programmers that do not come from a functional programming background, are there an mistakes to avoid?

    Good question. As Judah points out, the biggest one is that a query expression constructs a query, it does not execute the query that it constructs.

    An immediate consequence of this fact is executing the same query twice can return different results.

    An immediate consequence of that fact is executing a query the second time does not re-use the results of the previous execution, because the new results might be different.

    Another important fact is queries are best at asking questions, not changing state. Try to avoid any query that directly or indirectly causes something to change its value. For example, a lot of people try to do something like:

    int number; 
    from s in strings let b = Int32.TryParse(s, out number) blah blah blah
    

    That is just asking for a world of pain because TryParse mutates the value of a variable that is outside the query.

    In that specific case you'd be better to do

    int? MyParse(string s) 
    { 
        int result;
        return Int32.TryParse(s, out result) ? (int?)result : (int?)null;
    }
    ...
    from s in strings let number = MyParse(s) where number != null blah blah blah...
    

提交回复
热议问题