2017-09-13 14 views
1

3つの異なる状況で結果セットが同じ95%の状況があります。 5%の差は所与の変数に依存し、したがって残りの5%のフィールドを埋め込む(またはしない)。既存のIQueryableに複数の選択を追加する方法

簡単な例として、ここで返さ取得された結果オブジェクトである:

public class MyResults { 
    public string PropertyA { get; set; } 
    public string PropertyB { get; set; } 
    public string PropertyC { get; set; } 
    public string PropertyD { get; set; } 
    public string PropertyE { get; set; } 
} 

現在私は、次のしている結果を構築する方法があります:

public List<MyResults> GetMyResults(int someParameter) { 
    IQueryable<MyResults> query; 

    if (someParameter == "A") { 
    query = entities.Select(x => new MyResults { 
     PropertyA = x.PropertyA, // Common 
     PropertyB = x.PropertyB, // Common 
     PropertyC = x.PropertyC, // Different 
    }; 
    } else if (someParameter == "B") { 
    query = entities.Select(x => new MyResults { 
     PropertyA = x.PropertyA, // Common 
     PropertyB = x.PropertyB, // Common 
     PropertyD = x.PropertyD, // Different 
    }; 
    } else { 
    query = entities.Select(x => new MyResults { 
     PropertyA = x.PropertyA, // Common 
     PropertyB = x.PropertyB, // Common 
     PropertyE = x.PropertyE, // Different 
    }; 
    } 

    return query.ToList(); 
} 

をこれはですこれを行う方法:

public List<MyResults> GetMyResults(int someParameter) { 
    IQueryable<MyResults> query = entities.Select(x => new MyResults { 
    PropertyA = x.PropertyA, // Common 
    PropertyB = x.PropertyB, // Common 
    PropertyC = x.PropertyC, // Common 
    }; 

    if (someParameter == "A") { 
    query = entities.Select(x => new MyResults { 
     PropertyC = x.PropertyC // Different 
    }); 
    } else if (someParameter == "B") { 
    query = entities.Select(x => new MyResults { 
     PropertyD = x.PropertyD // Different 
    }); 
    } else { 
    query = entities.Select(x => new MyResults { 
     PropertyE = x.PropertyE // Different 
    }); 
    } 

    return query.ToList(); 
} 

このように、ALL結果の一貫性のあるフィールドは同じで、異なるものを追加するだけです。

これは可能ですか?次のように

+1

これは奇妙なにおいをします。なぜ、あなたは常に 'PropertyC'、' PropertyD'、そして 'PropertyE'を設定できませんか? –

答えて

3

あなたは三項演算子を使用することができます。

return entities.Select(x => new MyResults { 
    PropertyA = x.PropertyA, // Common 
    PropertyB = x.PropertyB, // Common 
    PropertyC = someParameter == 1 ? x.PropertyC : null, 
    PropertyD = someParameter == 2 ? x.PropertyD : null, 
    PropertyE = someParameter == 3 ? x.PropertyE : null, 
}).ToList(); 

基本的にstringのデフォルトとしてsomeParameterが与えられたpropertyXプロパティ値がnullとなりますためケースと一致しない場合nullです。そうであれば、それは望ましい値を得ます

+0

まあ、優れた点。これは動作します。上記のように、複数の「選択」を1つのクエリにマージする方法はありますか? – Grandizer

+1

@Grandizer - 良い方法ではない...あなたが実際に求めているものを「更新する」ことは、linqがそれにあまり合わないという理由で、下位の選択を行うためです。選択は新しいオブジェクトを投影するためのものです。だから、新しいオブジェクトを投影し、すべての共通プロパティを再度設定します。おそらく 'Aggregate'メソッドを使うことができますが、それはその目的ではありません。私はこれがきれいな方法だと思う。 –

+0

。ありがとう@ジラダ – Grandizer

関連する問題