Is it possible to reference to a property of the current object in a Select statement of a lambda expression in Linq?
Example:
...
.Select(s => new {
Date = s.Date.ToString("yyyy-MM-dd"),
Time = s.Time.ToString("h':'m"),
DateTime = s.Date.ToString("yyyy/MM/dd") +"-"+ s.Time.ToString("h':'m"),
Temperature = s.Temperature,
Humidity = s.Humidity,
Device = s.Device.Name,
Message = s.Message
})
I would like to replace the double call to the ToString function by referencing the previously defined Date and Time properties.
If you switch to LINQ query syntax (instead of method syntax), you could use the let keyword "to store the result of a sub-expression in order to use it in subsequent clauses".
from s in source
let dateStr = s.Date.ToString("yyyy-MM-dd")
let timeStr = s.Time.ToString("h':'m")
select new {
Date = dateStr,
Time = timeStr,
DateTime = dateStr + "-" + timeStr,
Temperature = s.Temperature,
Humidity = s.Humidity,
Device = s.Device.Name,
Message = s.Message
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With