Columns name will be in this list
List lstPrimary;--it will have the columns name
I am to use GroupBy clasue on DataTable using the columns which will be in this list "lstPrimary"
Thanks
Columns name will be in this list
List lstPrimary;--it will have the columns name
I am to use GroupBy clasue on DataTable using the columns which will be in this list "lstPrimary"
Thanks
Just doing the GroupBy, since datarows are type of object, will not group how you would expect. Instead you will need to implement IEqualityComparer and pass that into the GroupBy as well.
This code should be used as reference as there will be some changes you will probably want to make or be aware of the limitations. For one I haven't tested it against a data column of type Byte[], I only tested int, string, DateTime, decimal and I would guess it would fail unless the Byte[] was the same array. If you need that then you will need to change the IEqualityComparer and I would suggest looking at how MS does it for the DataRowComparer http://referencesource.microsoft.com/#System.Data.DataSetExtensions/System/Data/DataRowComparer.cs
The second thing you will want to look at changing is the hashcode code. This is just a simple hashcode check that just checks if the array lenghts are the same. If you want something better you can look at https://stackoverflow.com/a/3404820/1798889
public class DataRowValueComparer : IEqualityComparer<object[]>
{
public bool Equals(object[] x, object[] y)
{
// didn't test but this probably doesn't work if one of the datacolumns is a Byte[]
return x.SequenceEqual(y);
}
public int GetHashCode(object[] obj)
{
// You will want better hashcode
// can look at https://stackoverflow.com/a/3404820/1798889 for more info
return obj.Length.GetHashCode();
}
}
Now we can call GroupBy and use this to compare each datarows values
// group by passing in the IEqualityComparer
var grouped = dt.AsEnumerable().GroupBy(dr => lstPrimary.Select(col => dr[col]).ToArray(), new DataRowValueComparer());
The key will be an object[]