我需要用表达式参数实现过滤函数。 所以我无法将过滤后的查询应用于实体。
实体:
[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; }
}
按城市名称&#34;柏林&#34;过滤的测试用例。如何在函数中应用谓词。
public IConverter<T> Filter(Expression<Func<T, bool>> predicate)
{
// ???
return this;
}
答案 0 :(得分:0)
我认为您需要使用给定谓词过滤集合。
您可以定义一个Filter扩展方法,该方法将谓词作为参数(或者仅依赖于已存在的 collection.Where 扩展方法)
public static class Extensions
{
public static IEnumerable<T> Filter<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
return collection.Where(predicate);
}
}
根据您的需求定义谓词
// 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();
};
根据给定的谓词
过滤数据var query = from address in addresses
from city in address.Cities.Filter(berlin)
select city;