2017-12-05 11 views
0

표현식 매개 변수로 필터 함수를 구현해야합니다. 필터링 된 쿼리를 엔티티에 적용 할 수 없습니다.표현식 함수 적용

엔티티 : 도시 이름 "베를린"에 의해 필터링

[XmlRoot(ElementName = "Zip")] 
public class Zip 
{ 
    [XmlAttribute(AttributeName = "code")] 
    public string Code { get; set; } 
} 

[XmlRoot(ElementName = "District")] 
public class District 
{ 
    [XmlElement(ElementName = "Zip")] 
    public List<Zip> Zip { get; set; } 
    [XmlAttribute(AttributeName = "name")] 
    public string Name { get; set; } 
} 

[XmlRoot(ElementName = "City")] 
public class City 
{ 
    [XmlElement(ElementName = "District")] 
    public List<District> District { get; set; } 
    [XmlAttribute(AttributeName = "name")] 
    public string Name { get; set; } 
    [XmlAttribute(AttributeName = "code")] 
    public string Code { get; set; } 
} 

[XmlRoot(ElementName = "AddressInfo")] 
public class AddressInfo 
{ 
    [XmlElement(ElementName = "City")] 
    public List<City> City { get; set; } 
} 

테스트 케이스. 어떻게 함수로 술어를 적용 할 수 있습니까?

public IConverter<T> Filter(Expression<Func<T, bool>> predicate) 
{ 
    // ??? 
    return this; 
} 

답변

0

주어진 조건자를 사용하여 모음을 필터링해야한다고 가정합니다.

당신은

public static class Extensions 
{ 
    public static IEnumerable<T> Filter<T>(this IEnumerable<T> collection, Func<T, bool> predicate) 
    { 
     return collection.Where(predicate); 
    } 
} 

는 필요에 따라 조건을 정의 인수로 술어를 취하는 필터 확장 방법을 정의 (또는 이미 존재하는 collection.Where 확장 방법에 의존 간단히) 할 수

주어진 조건부

var query = from address in addresses 
      from city in address.Cities.Filter(berlin) 
      select city; 
012에 기초
// Filter by city Berlin 
Func<City, bool> berlin = city => city.Name == "Berlin"; 

// Filter by district Spandau 
Func<City, bool> spandau = city => city.Districts.Any(d => d.Name == "Spandau"); 

// Filter by zip 10115 
Func<City, bool> zipcode = city => 
{ 
    var predicate = from district in city.Districts 
        from zip in district.Zips 
        where zip.Code == "10115" 
        select zip; 

    return predicate.Any(); 
}; 

필터 데이터

enter image description here