0

Is there a way to achieve the same below output without using for/each loop? (using lambda expression?)

DataRow leftDataRow = GetReferenceDataRow();
DataTable table = GetTableForComparison():
List<NonMatchingValue> listColumnsWithDiscrepancies = new List<NonMatchingValue>();

foreach (DataRow row in table.Rows)
{
    for (int index = 0; index < table.Columns.Count; index++)
    {
        if (leftDataRow[index].ToString() != row[index].ToString())
        {
            listColumnsWithDiscrepancies.Add(new  NonMatchingValue {
                FieldSource = leftDataRow.Tables.Columns[index].ColumnName,
                FieldTarget = row.Table.Columns[index].ColumnName
                ValueSource = leftDataRow[index].ToString(),
                ValueTarget = row[index].ToString(),
                IsEqual = leftDataRow[index].Equal(row[index])
            });
        }
    }
}

The structure/number of columns of leftDataRow and rows in the table is identical.

// Sample Output:

FieldSource |   FieldTarget |   ValueSource |   ValueTarget |   IsEqual
-------------------------------------------------------------------------------
Column1     |   Column1     |   X           |   Y           |   False
Column2     |   Column2     |   A           |   A           |   True
yonan2236
  • 13,371
  • 33
  • 95
  • 141
  • Can you do a SQL query to fetch the rows? If yes, write the query as "where (col1 <> ?) or (col2 <> ?) or (col3 <> ?) ..." and supply the reference row values for the "?". With that, the database engine does the inner loop for you. – Dave S Jul 22 '21 at 16:22
  • @DaveS, not fetching data from database – yonan2236 Jul 22 '21 at 16:24
  • How many **columns** are present in the table (and reference row) ? – Steve Jul 22 '21 at 16:25
  • @Steve - rows from table and reference row are identical in structure. – yonan2236 Jul 22 '21 at 16:27
  • My idea is to search for the identical rows using the DataTable.Select method and then remove these identical rows from the table. The remaining rows are the different ones. Probably a loop will be still required but with a lot less of cycles. – Steve Jul 22 '21 at 16:29
  • Why do you not want to use a "for/each loop" ? – Luuk Jul 22 '21 at 16:31
  • Did you (try to) use [Linq](https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/working-with-linq) ? – Luuk Jul 22 '21 at 16:37
  • @Luuk - I'm not familiar with LINQ – yonan2236 Jul 22 '21 at 16:40
  • see: https://stackoverflow.com/a/47262860/724039, But also do read the other answers in that question, and give it a try. – Luuk Jul 22 '21 at 16:45

0 Answers0