将Linq查询结果与数组

时间:2017-07-21 13:42:08

标签: c# 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 :(得分:3)

看起来您的模型(selectedConfigCount)已知并且数据表中的列不是,因此您可以通过以下几种方式进行此操作:

您可以手动检查每个字段:

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

确保更改比较以满足您的要求(例如小写等)。

或者,如果要自动执行此操作,可以创建属性并使用它来装饰模型的属性。然后,您可以使用反射遍历查找此属性的属性,并使用它在列名列表中查找匹配项。

<强>更新

创建自定义属性:

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;
    }
相关问题