2016-06-30 5 views
1

나는 gelolocations의 목록이 있습니다. 목록에서 2 가지 조건을 수행하고 그 조건을 만족하는 조건을 선택하고 싶습니다. 나는 그것을하는 방법을 이해할 수 없다.여러 조건을 LINQ FirstOrDefault 메서드에 전달

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.

PostCode 위도 및 경도가 일치하지 않는 조건에서이 목록에 FirstOrDefault을 사용하고 싶습니다.

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>을 작성하고이를에 전달합니다.

+1

당신이 FirstOrDefault 내부 의견에 조건을 넣어 봤어 반환 할 수 있습니다? – raidensan

+1

나는 노력했지만 작동하지만 내 목표는'FirstOrDefault' 안에 모든 조건을 넣지 않는 것이다. 나는 'equals' 비교의 간단한 예를 들었다. 나는 매우 복잡한 조건을 가지고있다. 그들은 분명히 읽을 수 없습니다. 나는 그 조건들로 표현식을 만들고 그것을'FirstOrDefault'에 전달하려고합니다. – Venky

답변

0

감사합니다. 그것은 내가 올바른 방식으로 생각하도록 도왔다.

나는 이것을 좋아했다.

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

효과가 있고 코드가 훨씬 좋습니다.

+0

문제가 해결되면 질문에 대한 답을 표시하십시오. – Nsevens

2

당신은 당신의 자신의 대답을 준 :

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

FirstOrDefault는 예를 들어, 복잡한 람다를 수행 할 수 있습니다 응답들에 대한

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

+0

당신은 은밀한 구석 얻을 수 있습니다 : 'geolocationList.FirstOrDefault (g => { 경우 (g.PostCode.contains ("A")) { 복귀는 true, // 항상 "A" } 수익을 포함하는 포스트 코드를 받아 g.Latitude> 10; }' – daf

+0

'Func <>'을 사용하여 외부에서이 표현식을 빌드하고 'FirstOrDefault'에 매개 변수로 전달할 수있는 방법이 있습니까 – Venky

+1

익명 함수를 사용하지 않으려면 다음을 수행 할 수 있습니다. –

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

술어 유형 : System.Func 함수는 조건에 대한 각 요소를 테스트합니다.

그래서 당신은 TSource를 얻을 수있는 Func을 사용하고 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);