Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to the current object in a lambda expression

Tags:

c#

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.

like image 751
Carlos Blanco Avatar asked Jun 13 '26 15:06

Carlos Blanco


1 Answers

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 
}
like image 54
Douglas Avatar answered Jun 15 '26 05:06

Douglas