9

Silverlight にコンボ ボックスがあります。これには、LINQ-to-SQL オブジェクト (名前、住所、年齢など) の 1 つのプロパティから構築された値のコレクションがあります。コンボ ボックスで選択した値に基づいて結果をフィルター処理したいと考えています。

例: 姓が「Smith」の全員が必要だとします。ドロップダウン リストから [姓] を選択し、テキスト ボックス コントロールに smith と入力します。通常、次のようなLINQクエリを作成します...

var query = from p in collection
where p.LastName == textbox.Text
select p;

おそらくリフレクションを使用して、プロパティを動的に決定することは可能ですか? 何かのようなもの

var query = from p in collection
where p.(DropDownValue) == textbox.Text
select p;

4

3 に答える 3

19

仮定:

public class Person
{
    public string LastName { get; set; }
}

IQueryable<Person> collection;

あなたの質問:

var query =
    from p in collection
    where p.LastName == textBox.Text
    select p;

と同じ意味です:

var query = collection.Where(p => p.LastName == textBox.Text);

コンパイラはこれを拡張メソッドから次のように変換します。

var query = Queryable.Where(collection, p => p.LastName == textBox.Text);

の2番目のパラメータはQueryable.WhereですExpression<Func<Person, bool>>。コンパイラは型を理解し、ラムダを表す式ツリーExpression<>を構築するためのコードを生成します。

using System.Linq.Expressions;

var query = Queryable.Where(
    collection,
    Expression.Lambda<Func<Person, bool>>(
        Expression.Equal(
            Expression.MakeMemberAccess(
                Expression.Parameter(typeof(Person), "p"),
                typeof(Person).GetProperty("LastName")),
            Expression.MakeMemberAccess(
                Expression.Constant(textBox),
                typeof(TextBox).GetProperty("Text"))),
        Expression.Parameter(typeof(Person), "p"));

これがクエリ構文の意味です。

これらのメソッドは自分で自由に呼び出すことができます。比較対象のプロパティを変更するには、次のように置き換えます。

typeof(Person).GetProperty("LastName")

と:

typeof(Person).GetProperty(dropDown.SelectedValue);
于 2009-01-30T23:41:36.077 に答える
1

Scott Guthrie は、動的に構築された LINQ to SQL クエリに関する短いシリーズを公開しています。

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

これは簡単な方法ですが、もう少し複雑な別の方法があります。

http://www.albahari.com/nutshell/predicatebuilder.aspx

于 2009-01-30T21:00:46.887 に答える
0

私が作成したライブラリを使用することもできます: http://toasp.net/blog/dynamic-linq-queries.aspx。プロパティを ComboBox にラムダ式として格納し、次のように記述します。

var f = (Expression<Func<Product, string>>)comboBox.SelectedValue;
var query =
    from p in collection
    where f.Expand(textBox.Text)
    select p;
于 2009-02-12T01:46:40.843 に答える