2017-07-21 23 views
1

私はデータテーブルを受け入れ、データテーブルの列とデータベースの行の値を比較する必要があります。私の方法はこのように見えます。Linqクエリ結果と配列の比較

public bool CheckIfDataTableAndDataInTableMatch(DataTable resultTable, int selectedConfig) 
{ var selecetedConfigCount = DataAccess.Configurations.FindByExp(x => x.ConfigId == selectedConfigId) 
       .FirstOrDefault(); 
    var dataTableColumnNames = resultTable.Columns.Cast<DataColumn>() 
      .Select(x => x.ColumnName) 
      .ToArray(); 

    } 

私のクエリの結果はこれです。 enter image description here

私のデータテーブルからカラム名を取得した結果は次のとおりです。 enter image description here

私がしようとしているのは、クエリの値がデータテーブルの列と一致していることを確認することです。どのように私はこれらを比較するのだろうか?クエリの結果は常に1行になります。

+0

http://www.c-sharpcorner.com/UploadFile/87b416/linq-expect-intersect-and-union-method-operator-in-C-Sharp/ –

+0

「データテーブル」に値を含むクエリを含めるようにしてください。 – summerGhost

+0

厳密な比較ですか?ポジションはどうですか?名前がすべてそこにあるときは大丈夫ですか?=! –

答えて

3

それはあなたのモデル(selectedConfigCount)が知られているように見え、あなたはこのいくつかの方法については行くことができますので、データテーブルの列は、ありません。

var exists = dataTableColumnNames.Any(n => n == selectedConfigCount.EE_City__); 

あなたが手動で各フィールドを確認することができます

要件を満たすために比較を変更してください(小文字など)。

または、これを自動化する場合は、属性を作成し、その属性を使用してモデルのプロパティを飾ることができます。その後、リフレクションを使用して、この属性を探しているプロパティを調べ、それを使用して列名のリスト内の一致を見つけることができます。

UPDATE:

は、カスタム属性を作成します。

public class ColumnMatchAttribute : Attribute 
{ 

} 

は、モデルのプロパティにこの属性を適用します。

[ColumnMatch] 
public string EE_City__ { get; set; } 

は、プロパティをチェックし、比較機能を持っていますあなたのため:

private static bool CompareFields(Config selectedConfigCount, DataTable table) 
    { 
     var columns = table.Columns.Cast<DataColumn>().Select(c => c.ColumnName); 
     var properties = selectedConfigCount.GetType().GetProperties(); 
     foreach (var property in properties) 
     { 
      var attributes = property.GetCustomAttributes(true); 
      foreach (var attribute in attributes) 
      { 
       if (attribute.GetType() == typeof(ColumnMatchAttribute)) 
       { 
        //This property should be compared 
        var value = property.GetValue(selectedConfigCount); 
        if (value == null) 
         return false; 

        //Change this comparison to meet your requirements 
        if (!columns.Any(n => n == value.ToString())) 
         return false; 
       } 
      } 
     } 
     return true; 
    } 
+0

これは、探しているものに近いです。 –

+0

@ LeonardoTrimarchi:コードサンプルを使用して回答を更新しました。 – JuanR

+0

これはかなりきれいです、私の比較は、値がdatatableからの列名と一致するはずです。私はyoureがあなたのコードで正しいものを正しいと思いますか? @Juan –

関連する問題