2017-05-17 5 views
0

私は4列のテーブルを返すクエリ可能なクエリを持っています:フィルタ列IQueryable C#

ItemName |国A |国B |国C |

私のアプリにはいくつかの認証プロセスがあり、一部のユーザーは特定の国の列のみを表示する必要があります。例えば

、請求国とユーザー= Aのみが表示されるはずです。

ItemNameのを|国A |

カラムの名前に基づいてカラムをフィルタリングする方法はありますか?

IQueryable<AllCountries> ResultsVM = _context.AllCountries; 
      var country = IdentityExtensions.GetCountryId(User);    

      if (country != null) 
      { 
       Type elementType = ResultsVM.ElementType; 
       foreach (PropertyInfo pi in elementType.GetProperties()) 
       { 

         if (country==pi.Name) 
         { 
          ResultsVM= _context.AllCountries 
              .Select(t => new AllCountries 
            {           
             ItemName=t.ItemName, 
             ?? only the column which matches the country 
            }); 
         } 

       } 

      }  

これまでのところ、私は私のIQueryableの列は、ユーザの国に対応する際に知っているが、私はそれを表示する方法を私の選択に知っているし、他の人を削除しないでください...

更新のIQueryableを格納し、私のMVC Webプロジェクトで私のビューで使用されます

私のViewModelにResultsVMは、リストのように定義されます。

public class AllCountries 
    {  
     [DisplayName("Item")] 
     public string ItemName { get; set; } 
     public int? Country1 { get; set; } 
     public int? Country2 { get; set; } 
     public int? Country3 { get; set; }   
    } 
Country + '1' 
Country + '2' 
Country + '3' 
Country + '4' 

次にあなたが作成することができます:は、列の名前の接頭辞を考慮

シルヴァン

答えて

0

は国であり、あなたがその列を選択したい条件は例のために、その列の接尾辞ですありがとう私はCを取得するためにReflectionを使用しているSELECT文で

public class Country 
     { 
      public string Condition { get; set; } 
      public string Country1 { get; set; } 
      public string Country2 { get; set; } 
      public string Country3 { get; set; } 
     } 

public void GetData() 
     { 
      List<Country> liCountry = new List<Country>(); 
      liCountry.Add(new Country { Condition = "1", Country1 = "2", Country2 = "3", Country3 = "4" }); 
      liCountry.Add(new Country { Condition = "2", Country1 = "20", Country2 = "30", Country3 = "40" }); 
      liCountry.Add(new Country { Condition = "3", Country1 = "21", Country2 = "31", Country3 = "41" }); 
      string temp = "2"; 
      var liResult = liCountry.Where(w => w.Condition == temp).Select(s => new {result = s.GetType().GetProperty("Country" + temp).GetValue(s, null) }).ToList(); 

     } 

:このようなあなたのLINQクエリ内の動的選択列名を動的に変更します。

+0

ありがとうございます。どのようにして、汎用の「結果」列名ではなく、正しい列名(例:country2)を含む結果を返すにはどうすればよいでしょうか?私の視点でマッピングを行うためには、私にとって重要です。 – sylvain77

+0

@ sylvain77はあなたが求めているものを手に入れませんでした。詳細を教えてください。 –

+0

確かに。私は私の質問を更新しました。私のIList resultsVMは私の質問で定義されたクラスに基づいている必要があります。あなたの例では、liResultを "country2"とし、リスト内の私の列のタイトルであり、あなたの例では "result"ではありません。私は私の視野の中でそれを使用するために、命名の一貫性を保つ必要があります。 – sylvain77