简体   繁体   English

C#三元运算符?:效率

[英]C# Ternary operator ?: efficiency

I am using the ternary operator but it has big performance inefficiencies is there an equivalent solution to solve the in-efficiency? 我正在使用三元运算符,但是它的效率低下,是否有等效的解决方案来解决效率低下的问题?

Given we have two lists and we wish to select from one using linq: 鉴于我们有两个列表,我们希望使用linq从其中一个列表中进行选择:

var myList1 = new List<string>();
var myList2 = new List<string>();

var result = 
      myList1.Select(x => new {
      Id = x,
      Count = myList2.Count(y => y == x) == 0 ? "Not Found" 
                                              : myList2.Count(y => y == x).ToString()
      });

Now with the ternary operator ?: I have shown here the linq expression will check if the count is 0 first and display "Not Found" else it will run the linq count again and show the result. 现在使用三元运算符?:我已经在这里显示linq表达式将首先检查计数是否为0并显示“未找到”,否则它将再次运行linq计数并显示结果。 My point is that it will be running the linq query twice when effectively it only needs to store the value and use it again in the else. 我的观点是,它将在有效时仅运行一次linq查询两次,而只需要存储该值并在else中再次使用它。 This seems hugely in-efficient if the linq query was somewhat larger and more complex. 如果linq查询更大,更复杂,这似乎效率很低。

I know the ternary operator should only be used for simple equations eg i > 1 ? 我知道三元运算符应仅用于简单的方程式,例如i> 1? true : false but what is an alternative to have this within a linq query as I cannot store the value first to use again. true:false,但是在linq查询中具有此选项的替代方法是,我无法先存储该值以再次使用。

Update: 更新:

This is a theoretical question regarding the ternary operator given that it needs to run the same equation twice if the condition applies. 这是一个关于三元运算符的理论问题,因为如果条件适用,它需要两次运行相同的方程式。 Too in-efficient to use when the equation is large and complex ? 当方程大而复杂时,使用效率太低?

I cannot store the value first to use again 我无法先存储值再使用

Why not? 为什么不? You sure can. 你当然可以。

var result = myList1.Select(x => {
    var count = myList2.Count(y => y == x);
    return new {
        Id = x,
        Count = count == 0 ? "Not Found" : count.ToString();
    };
});

You can also do this using query syntax taking advantage of let clause: 您也可以利用查询语法利用let子句来做到这一点:

var result = from e in myList1
             let count = myList2.Count(y => y == e)
             select new { Count = count == 0 ? "Not Found" : count.ToString()};

You can keep the count result in a variable, so you don't count 2 times for each row in myList1. 您可以将计数结果保存在变量中,因此您不会对myList1中的每一行进行2次计数。 Code: 码:

var myList1 = new List<string>();
var myList2 = new List<string>();
int counter = 0;
var result = 
      myList1.Select(x => new {
          Id = x
          Count = (counter = myList2.Count(y => y == x)) == 0 ? "Not Found" : counter.ToString()
      });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM