LINQで式を理解しようと夢中になっています。どんな助けでも大いに感謝しています(私がここで完全にオフになっていると言っても)。LINQのネストされた汎用Lambda
のは、私は、その後作成するようLocations.NameやLocations.Floor、またはEducations.SchoolNameとして文字列を取り込み方法を、作成しようとしている三つのクラス
public class Person
{
public string Name { get; set;}
public IEnumerable<PersonLocation> Locations { get; set;}
public IEnumerable<PersonEducation> Educations { get; set:}
}
public class PersonLocation
{
public string Name { get; set;}
public string Floor { get; set;}
public string Extension { get; set;}
}
public class PersonEducation
{
public string SchoolName { get; set;}
public string GraduationYear { get; set;}
}
を持っているとしましょう動的LINQクエリ
IEnumerable<Person> people = GetAllPeople();
GetFilteredResults(people, "Location.Name", "San Francisco");
GetFilteredResults(people, "Location.Floor", "17");
GetFilteredResults(people, "Educations.SchoolName", "Northwestern");
people.Where(p => p.Locations.Any(pl => pl.Name == Value);
I Hにほぼ等しい式を作成する必要があり、このGetFilteredResults(IEnumerable<Person> people, string ModelProperty, string Value)
方法
string[] modelPropertyParts = ModelProperty.Split('.');
var prop = typeof(Person).GetProperty(modelPropertyParts[0]);
var sourceParam = Expression.Parameter(typeof(Person), "person");
var expression = Expression.Equal(Expression.PropertyOrField(sourceParam, modelPropertyParts[0]), Expression.Constant(option.Name));
var whereSelector = Expression.Lambda<Func<Person, bool>>(orExp, sourceParam);
return people.Where(whereSelector.Compile());
私はIEnumerableをタイプするためにで遊んでてきたものだが、私:ModelPropertyは、文字列、すなわちpeople.Whereた(p => p.Name ==値)である場合は、この作業をaveが、このようになります。問題はSystem.Linq.Enumerable.Any
は、静的な拡張メソッドであるということです
/*i.e. modelPropertyParts[0] = Locations & modelPropertyParts[1] = Name */
string[] modelPropertyParts = ModelProperty.Split('.');
var interiorProperty = prop.PropertyType.GetGenericArguments()[0];
var interiorParameter = Expression.Parameter(interiorProperty, "personlocation");
var interiorField = Expression.PropertyOrField(interiorParameter, modelPropertyParts[1]);
var interiorExpression = Expression.Equal(interiorField, Expression.Constant(Value));
var innerLambda = Expression.Lambda<Func<PersonLocation, bool>>(interiorExpression, interiorParameter);
var outerParameter = Expression.Parameter(typeof(Person), "person");
var outerField = Expression.PropertyOrField(outerParameter, modelPropertyParts[0]);
var outerExpression = ??
var outerLambda == ??
return people.Where(outerLambda.Compile());
恐縮です!それは基本的にうまくいきました。唯一の問題は、渡すタイプが間違っていることです。これはtypeof(Person)の代わりにinteriorPropertyでなければなりません –
ああ、私は今見ます。お気軽に答えを修正してください(コミュニティのwiki) –