[英]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.