0

Currently I do this to validate if an item is present in the list

var wifiSSID = userLocation.LocationWiFiSSIDs.Where(x => x.WiFiSSID == attendanceDto.WiFiSSID).FirstOrDefault();
if (IsWiFiSSIDEnabled && wifiSSID == null)
{
    throw new ApplicationException(ErrorMessages.InvalidWiFiSSID);
}

Can I write this in better way? With Any or Contains?

Krishnandu Sarkar
  • 494
  • 1
  • 6
  • 21

2 Answers2

2

Assuming that wifiSSID is only used for validation in your code, then you can use Any() as follows :

if (IsWiFiSSIDEnabled && !userLocation.LocationWiFiSSIDs.Any(x => x.WiFiSSID == attendanceDto.WiFiSSID)
{
    throw new ApplicationException(ErrorMessages.InvalidWiFiSSID);
}

This way userLocation will be checked only if IsWiFiSSIDEnabled is true.

har07
  • 88,338
  • 12
  • 84
  • 137
2

Use all

if (IsWiFiSSIDEnabled && userLocation.LocationWiFiSSIDs.All(x => x.WiFiSSID != attendanceDto.WiFiSSID)
{
    throw new ApplicationException(ErrorMessages.InvalidWiFiSSID);
}
jitender
  • 10,238
  • 1
  • 18
  • 44