将多个条件传递给LINQ FirstOrDefault方法

本文关键字:LINQ FirstOrDefault 方法 条件 | 更新日期: 2023-09-27 17:53:38

我有一个gelolocations的列表。我想在列表中执行2个条件,并选择满足这些条件的条件。我不知道该怎么做。

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

我想在此列表geolocationList上执行多个条件。

我想在这个列表中使用FirstOrDefault,条件是PostCode属性与提供的属性匹配,经度、纬度不为空。

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

我想在外部构建这个conditions,并将其作为参数传递给FirstOrDefault。例如构建CCD_ 7并将其传递到。

将多个条件传递给LINQ FirstOrDefault方法

您已经给出了自己的答案:

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

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

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

感谢你们的回复。它帮助我以正确的方式思考。

我确实喜欢这个。

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

它起作用了,代码也好多了。

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

谓词类型:System.Func测试每一个的函数条件的元素。

因此,您可以使用任何获得TSource并返回bool 的Func

//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);