C
C#•2mo ago
SWEETPONY

Is it possible to use pattern matching here?

I want smth like this:
var isInbound = entity.LegData!.Location.LatestArrivalStationIataCode == "SVO";
var isOutbound = entity.LegData!.Location.LatestDepartureStationIataCode == "SVO";

return new PresentationModel
{
Terminal =
isInbound => entity.LegData!.Location.ArrivalTerminal
isOutbound => entity.LegData!.Location.DepartureTerminal
}
var isInbound = entity.LegData!.Location.LatestArrivalStationIataCode == "SVO";
var isOutbound = entity.LegData!.Location.LatestDepartureStationIataCode == "SVO";

return new PresentationModel
{
Terminal =
isInbound => entity.LegData!.Location.ArrivalTerminal
isOutbound => entity.LegData!.Location.DepartureTerminal
}
5 Replies
SWEETPONY
SWEETPONYOP•2mo ago
var terminal = (isInbound, isOutbound) switch
{
(false, true) => "Inbound",
(true, false) => "Outbound",
_ => ""
};
var terminal = (isInbound, isOutbound) switch
{
(false, true) => "Inbound",
(true, false) => "Outbound",
_ => ""
};
i know this but it looks ugly
Angius
Angius•2mo ago
I was about to propose exactly that lol
SWEETPONY
SWEETPONYOP•2mo ago
i was faster 🙂
FestivalDelGelato
FestivalDelGelato•2mo ago
you could add names, like
(isInbound: false, isOutbound: true) => ...,
(isInbound: true, isOutbound: false) => ...,
_ => oopsie
(isInbound: false, isOutbound: true) => ...,
(isInbound: true, isOutbound: false) => ...,
_ => oopsie
to me that helps it would be great if you could assign constants like
const (bool, bool) Inbound = (true, false);
var terminal = (isInbound, isOutbound) switch {
Inbound => "Inbound",
...
};
const (bool, bool) Inbound = (true, false);
var terminal = (isInbound, isOutbound) switch {
Inbound => "Inbound",
...
};
but you can't bu you could 'parse' it, although this starts to be too much for me (maybe) or you can wait for discriminated unions (sarcasm)
SleepWellPupper
SleepWellPupper•2mo ago
Here's another pattern:
return new PresentationModel
{
Terminal = entity.LegData?.Location switch
{
{ LatestArrivalStationIataCode: "SVO", LatestDepartureStationIataCode: not "SVO" } arrivalLocation => arrivalLocation.ArrivalTerminal,
{ LatestArrivalStationIataCode: not "SVO", LatestDepartureStationIataCode: "SVO" } departureLocation => departureLocation.DepartureTerminal,
_ => throw new InvalidOperationException("no location provided or invalid station codes set")
}
};
return new PresentationModel
{
Terminal = entity.LegData?.Location switch
{
{ LatestArrivalStationIataCode: "SVO", LatestDepartureStationIataCode: not "SVO" } arrivalLocation => arrivalLocation.ArrivalTerminal,
{ LatestArrivalStationIataCode: not "SVO", LatestDepartureStationIataCode: "SVO" } departureLocation => departureLocation.DepartureTerminal,
_ => throw new InvalidOperationException("no location provided or invalid station codes set")
}
};
Could use some terseness with the variable names I suppose. Note that for this one to work, the "SVO" string needs to be a constant.

Did you find this page helpful?