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:
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. 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. This seems hugely in-efficient if the linq query was somewhat larger and more complex.
I know the ternary operator should only be used for simple equations e.g. 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.
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 ?