It seems to me that working with DataTables
is not easy as lots of casting is needed in order to extract anything more meaningful than an object from them. I would do something like this to get the required column names from table1
.
var rows = table1.AsEnumerable();
var colNames = rows.Where(r => (string)r["colGroup"] == "YES" || (string)r["colGroup"] == "OK")
.Select(r => r.Field<string>("columnName"));
Now query table2
accessing the relevant Column by using the Row Indexer
that takes a string to index into the Columns.
var comparer= new IEnumerableEqualityComparer<object>();
var query = table2.AsEnumerable()
.GroupBy(row =>; colNames.Select(name =>; row[name]), comparer)
.Select(group =>;(Keys:group.Key, Count :group.Count()));
You can enumerate the query like this
foreach (DataRow row in table2.Rows)
{
foreach (DataColumn column in table2.Columns)
{
Console.WriteLine(row[column]);
}
}
My generic comparer is too simplistic. Search for IEqualityComparer for SequenceEqual for some better examples
public class IEnumerableEqualityComparer<T> : IEqualityComparer<IEnumerable<T>>
{
public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(IEnumerable<T> items)
{
unchecked
{
int hash = 17;
foreach (var item in items)
{
hash = hash * 31 + item.GetHashCode();
}
return hash;
}
}
}