错误的表达结果linq

时间:2015-12-08 07:29:25

标签: c# .net linq lambda

我想用parentIds获取记录。但是这个Linq表达式给了我带有0 parentId值的元素。

var orders =
    OrderEquityTransactions.AsParallel().Where(
        o => o.FinancialInstrumentId == financialInstrumentPrice.FinancialInstrumentId &&
            o.ParentId != 0 &&
        (o.DebitCredit == "A" ? o.Price >= financialInstrumentPrice.Price : o.Price <= financialInstrumentPrice.Price)).ToList();

经过一番挖掘后,我用另外两个括号重写了表达式并解决了问题。

private JSONObject uploadToServer() throws IOException, JSONException {
            String query = "https://example.com";
            String json = "{\"key\":1}";

            URL url = new URL(query);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            os.close();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
            JSONObject jsonObject = new JSONObject(result);


            in.close();
            conn.disconnect();

            return jsonObject;
    }

这种行为的原因是什么?

2 个答案:

答案 0 :(得分:4)

因为在第一种情况下它被解释为:

o => (o.FinancialInstrumentId == financialInstrumentPrice.FinancialInstrumentId 
   && o.ParentId != 0 && o.DebitCredit == "A") 
  ? o.Price >= financialInstrumentPrice.Price 
  : o.Price <= financialInstrumentPrice.Price

这绝对是另一个。

请阅读有关运营商优先权的this article 三元条件运算符的优先级低于条件AND。

答案 1 :(得分:3)

根据Operator precedence and associativity,条件AND的优先级高于条件运算符。所以C#会像这样评估你的表达式:

(o.FinancialInstrumentId == financialInstrumentPrice.FinancialInstrumentId 
        && o.ParentId != 0 && o.DebitCredit == "A")
    ? o.Price >= financialInstrumentPrice.Price
    : o.Price <= financialInstrumentPrice.Price