[英]passing Multiple conditions to LINQ FirstOrDefault Method
我有一个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
属性与提供的属性匹配,并且Longitude,lattitude不为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
我想在外面构建这个conditions
并将其作为参数传递给FirstOrDefault
。 例如,建立一个Func<input, output>
并将其传递给。
你给出了自己的答案:
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
)
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.