Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding Condition if Parameter is null

I am fetching data using LINQ and Lambda with 2 conditions using this Query. Is it possible to write this logic without if else condition -

public List<Pallet> GetPallet(string palletID, string locationID)
{
    List<Pallet> data = new List<Pallet>();

    if (locationID != null)
        data = data.Where(x => x.PalletID == palletID && x.LocationID == locationID).ToList();
    else
        data = data.Where(x => x.PalletID == palletID).ToList();

    return data;
}
like image 487
artista_14 Avatar asked Jan 19 '26 11:01

artista_14


1 Answers

Sure it is:

public List<Pallet> GetPallet(string palletID, string locationID)
{
    List<Pallet> data = new List<Pallet>();
    data = data.Where(x => x.PalletID == palletID && (locationID == null || x.LocationID == locationID)).ToList();

    return data;
}
like image 66
Tomas Chabada Avatar answered Jan 21 '26 00:01

Tomas Chabada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!