Leonardo Wildt
Leonardo Wildt

Reputation: 2599

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. enter image description here

The result from getting the column names from my data table is this. enter image description here

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.

Upvotes: 1

Views: 743

Answers (1)

JuanR
JuanR

Reputation: 7783

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 (e.g. 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;
    }

Upvotes: 3

Related Questions