I have a telerik grid that I databind a list of objects to on a page. The users can group columns to their liking when viewing the data. I am writing a function to export this data in an excel document and would like to preserve the grouping that the user has on the page. I am able to get the string names of the properties of my objects that the user has grouped by.
What I am stuck on is how to do the grouping during runtime. There are plenty of examples such as this: Group by with multiple columns using lambda describing how to group by multiple properties during compile time when you know ahead of time. I however, do not know what to group by until during run time.
Is there any suggestions on how to go about grouping during runtime?
You're probably looking for something like the answer to this SO question, notably:
var myData = gridData.AsEnumerable()
.GroupBy(r => r, new MyDataComparer(keys))
.ToList();
internal class MyDataComparer : IEqualityComparer<MyDataType>
{
private readonly string[] _keys;
public MyDataComparer(string[] keys)
{
_keys = keys; // keep the keys to compare by.
}
public bool Equals(MyDataType x, MyDataType y)
{
// a simple implementation that checks if all the required fields
// match. This might need more work.
bool areEqual = true;
foreach (var key in _keys)
{
areEqual &= (x[key].Equals(y[key]));
}
return areEqual;
}
public int GetHashCode(DataRow obj)
{
// Add implementation here to create an aggregate hashcode.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With