8

特定のオブジェクトのパブリック プロパティをドロップダウンに入力したいのですが、これはうまくいきました。しかし、ユーザーがドロップダウンから値を選択すると、DB テーブルの結果をその列でグループ化する必要があります。LINQ を使用してみましたが、リフレクション プロパティではなく、インスタンス変数プロパティによって明示的にグループ化する方法しかわかりません。これが私のメソッドです。渡されるパラメーターは、プロパティの文字列名です。たとえば、ユーザーが Customer.Country でグループ化する場合は「Country」になり、ユーザーが Customer.State でグループ化する場合は「State」になります。しかし、現時点では、LINQ クエリで渡された文字列値を使用する方法がわからないため、「状態」でグループ化するようにハードコーディングしています。

private void DisplayReportAction(string category)
{
    if (!string.IsNullOrEmpty(category))
    {
        SelectedCategory = category;
        _summaries.Clear();

        foreach (var custGroup in _customerInterface.CustomerInterface.GetAllCustomers().GroupBy(c => c.State)
            .Select(group => new
                                 {
                                     Category = group.Key,
                                     Count = group.Count()
                                 })
                                 .OrderBy(x => x.Category))
        {
            _summaries.Add(new CustomerReportSummaryViewModel(custGroup.Category, custGroup.Count));
        }

        ReportVisibility = Visibility.Visible;
    }
}
4

2 に答える 2

21

LINQ to Objects を使用している場合は、Reflection を使用できます。たとえば、次のように使用できます。

_customerInterface.CustomerInterface.GetAllCustomers()
     .GroupBy(c => c.GetType().GetProperty(category).GetValue(c, null))

Linq To Sql を使用している場合は、代わりに動的クエリを使用することもできます。このリンクを確認してください。

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

于 2013-10-23T11:55:45.253 に答える
3

式を動的に構築することができます:

    Expression<Func<Customer,T>> buildExpression<T>(string category)
    {
        //First build parameter of lambda ( 'c =>' part of expression)
        ParameterExpression param = Expression.Parameter(typeof(Customer), "c");
        //Then body of expression : ' => c.category'
        Expression<Func<Customer, T>> exp = Expression.Lambda<Func<Customer, T>>(Expression.Property(param, category), param);
        return exp;
    }

そして最後に、電話

_customerInterface.CustomerInterface.GetAllCustomers()
    .GroupBy(buildExpression(category))

編集: 申し訳ありませんが、buildExpression関数に T 型パラメーターを与えるには、プロパティの型を知る必要があります。

これを行う方法はいくつかあります。たとえば、 を使用してonGetProperty(category).PropertyTypeを呼び出しますが、これにはもう少し作業が必要です。とにかく、このタイプから構築する方法を見つける必要があります。MakeGenericMethodGetType().GetMethod("buildExpression<>")CustomerReportSummaryViewModel

ユースケースはわかりませんが、おそらくすべてのカテゴリプロパティが同じタイプであるため、ハードコーディングできますか?

興味があり、それを行う適切な方法が見つからない場合は、私に知らせてください。適切な解決策を書きます。

于 2013-10-23T12:13:07.817 に答える