Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping by multiple keys known at runtime

Tags:

c#

.net

linq

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?

like image 667
Justin Avatar asked Nov 01 '22 14:11

Justin


1 Answers

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.
    }
}    
like image 74
Corey Adler Avatar answered Nov 15 '22 05:11

Corey Adler