artista_14
artista_14

Reputation: 716

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;
}

Upvotes: 3

Views: 3188

Answers (2)

A-Sharabiani
A-Sharabiani

Reputation: 19329

This is a way of doing it with correct results:

data = data
.Where(x => x.PalletID == palletID)
.Where(!string.IsNullOrEmpty(locationID)? x.LocationID == locationID : true)
.ToList();

NOTE: The accepted answer will return the wrong result although the syntax is correct. It'll always compares the LocationID even if the locationID is null or empty. Note that, in case of locationID == null we do not want to compare at all (we don't want this: x => x.LocationID == null).

Upvotes: 0

Tomas Chabada
Tomas Chabada

Reputation: 3019

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;
}

Upvotes: 8

Related Questions