简体   繁体   中英

passing Multiple conditions to LINQ FirstOrDefault Method

I have a list of gelolocations . I want to perform 2 conditions on the list and select the ones which satisfy those conditions. I cannot figure out how to do that.

public class GeolocationInfo
{
    public string Postcode { get; set; }

    public decimal Latitude { get; set; }

    public decimal Longitude { get; set; }
}

var geolocationList = new List<GeolocationInfo>(); // Let's assume i have data in this list

I want to perform multiple conditions on this list geolocationList .

I want to use FirstOrDefault on this list on the conditions that PostCode property matching with the one supplied and Longitude, lattitude are not null.

    geolocationList .FirstOrDefault(g => g.PostCode  == "AB1C DE2"); 
// I want to add multiple conditions like  g.Longitude != null && g.Lattitude != null in the same expression

I want to build this conditions outside and pass it as a parameter to FirstOrDefault . eg like building a Func<input, output> and passing this into.

你给出了自己的答案:

geoLocation.FirstOrDefault(g => g.Longitude != null && g.Latitude != null);

FirstOrDefault可以采用复杂的lambda,例如:

geolocationList.FirstOrDefault(g => g.PostCode == "ABC" && g.Latitude > 10 && g.Longitude < 50);

Thanks for your response guys. It helped me think in the right way.

I did like this.

Func<GeolocationInfo, bool> expression = g => g.PostCode == "ABC" &&
                                              g.Longitude != null &&
                                              g.Lattitude != null;
geoLocation.FirstOrDefault(expression);

It worked and code is much better.

public static TSource FirstOrDefault<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> predicate
)

predicate Type: System.Func A function to test each element for a condition.

So you can use any Func that get TSource and return bool

//return all
Func<GeolocationInfo, bool> predicate = geo => true;

//return only geo.Postcode == "1" and geo.Latitude == decimal.One
Func<GeolocationInfo, bool> withTwoConditions = geo => geo.Postcode == "1" && geo.Latitude == decimal.One;

var geos = new List<GeolocationInfo>
{
    new GeolocationInfo(),
    new GeolocationInfo {Postcode = "1", Latitude = decimal.One},
    new GeolocationInfo {Postcode = "2", Latitude = decimal.Zero}
};

//using
var a = geos.FirstOrDefault(predicate);
var b = geos.FirstOrDefault(withTwoConditions);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM