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

C# 将多个条件传递给LINQ FirstOrDefault方法,c#,linq,geolocation,C#,Linq,Geolocation,我有一个gelolocations列表。我想在列表中执行2个条件,并选择满足这些条件的条件。我不知道该怎么做 public class GeolocationInfo { public string Postcode { get; set; } public decimal Latitude { get; set; } public decimal Longitude { get; set; } } var geolocationList = new List<

我有一个
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

我想在外部构建这个
条件
,并将其作为参数传递给
FirstOrDefault
。e、 例如构建一个
Func
并将其传递到中。

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

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

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


geolocationList.FirstOrDefault(g=>g.PostCode==“ABC”&g.纬度>10&g.经度<50)

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

我确实喜欢这个

Func<GeolocationInfo, bool> expression = g => g.PostCode == "ABC" &&
                                              g.Longitude != null &&
                                              g.Lattitude != null;
geoLocation.FirstOrDefault(expression);
Func expression=g=>g.PostCode==“ABC”&&
g、 经度!=空的&&
g、 格子!=无效的
地理定位。第一个默认值(表达式);

它成功了,代码也更好了

您是否尝试过将条件放在FirstOrDefault中的注释中?我尝试过,但我的目标是不要将所有条件放在
FirstOrDefault
中。我给出了一个简单的
equals
比较示例。我的情况很复杂。它们绝对不可读。我想用这些条件构建一个
表达式
,并将它们传递到
FirstOrDefault
。您甚至可以变得更狡猾:
geolocationList.FirstOrDefault(g=>{if(g.PostCode.contains(“A”){return true;//始终接受包含“A”}的邮政编码返回g.Latitude>10;})
是否有任何方法可以使用
Func
在外部构建此表达式,并将其作为参数传递给
FirstOrDefault
如果您不想使用匿名函数,可以尝试
geolocationList.FirstOrDefault(g=>IsParameterOk(g))
然后
bool IsParameterOk(GeolocationInfo g){/*logic here*/}
当然,您可以定义自己的函数
public bool FirstOrDefaultFilter(GeolocationInfo GeolocationInfo)
然后使用它:
geolocationList.FirstOrDefault(FirstOrDefaultFilter)
@KamilT在这种情况下,我们不需要lambda
g=>IsParameterOk(g)
IsParameterOk
的签名与lambda所需的
Func
相同。如果问题已解决,请标记问题的答案。
public static TSource FirstOrDefault<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> predicate
)
public static TSource FirstOrDefault<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> predicate
)
//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);