How can we implement the `let` keyword in C#
gordonwatts opened this issue · 0 comments
gordonwatts commented
The let
keyword is syntatic sugar, but it makes expressions a lot more readable (see LINQ documentation).
Here is an example from their documentation:
class LetSample1
{
static void Main()
{
string[] strings =
{
"A penny saved is a penny earned.",
"The early bird catches the worm.",
"The pen is mightier than the sword."
};
// Split the sentence into an array of words
// and select those whose first letter is a vowel.
var earlyBirdQuery =
from sentence in strings
let words = sentence.Split(' ')
from word in words
let w = word.ToLower()
where w[0] == 'a' || w[0] == 'e'
|| w[0] == 'i' || w[0] == 'o'
|| w[0] == 'u'
select word;
// Execute the query.
foreach (var v in earlyBirdQuery)
{
Console.WriteLine("\"{0}\" starts with a vowel", v);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
We ran into this when translating the CMS Higgs stuff - and wanted to re-write the following C++ code into LINQ:
for (int i = 0; i < p.numberOfHits(); i++)
{
uint32_t hit = p.getHitPattern(i);
// if the hit is valid and in pixel
if (p.validHitFilter(hit) && p.pixelHitFilter(hit)) {GM_PixelHits++;}
if (p.validHitFilter(hit)) {GM_ValidHits++;}
}