简体   繁体   中英

Compare Linq Query Result to Array

I have a method that accepts a data table and i need to compare the columns from the datatable to values in a row from the database. My method looks like this.

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();

   }

The result from my query is this. 在此输入图像描述

The result from getting the column names from my data table is this. 在此输入图像描述

What i am trying to do is to make sure that the values in the query match the columns from the data table. How would i compare these? The result from the query will always be one row.

It looks like your model (selectedConfigCount) is known and the columns from the data table are not, so you can go about this a few ways:

You can manually check each field:

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

Make sure to change the comparison to satisfy your requirements (eg lower case, etc).

Or, if you want to automate this, you could create an attribute and decorate the properties of the model with it. You could then use reflection to go through the properties looking for this attribute and use it to find a match in the list of column names.

UPDATE:

Create a custom attribute:

public class ColumnMatchAttribute : Attribute
{

}

Apply this attribute to the properties of the model:

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

Have a function that checks the properties and compares for you:

    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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM