An issue with LINQ Group by query

36 Views Asked by At

I have a query which works fine

  private ObservableCollection<Grouping<string, SEListItemTemplate>> MonkeysGrouped { get; set; }


            var sorted = from item in CollPublic
                         orderby item.Title
                         group item by item.Title into listData
                         select new Grouping<string, SEListItemTemplate>(listData.Key, listData);

            MonkeysGrouped = new ObservableCollection<Grouping<string, SEListItemTemplate>>(sorted);

            list.ItemsSource = MonkeysGrouped;

If now I want to use Custom Sorting & Grouping Functions, something like below, how can I do this?

var sorted = from item in CollPublic
                         orderby (OrderByFunc)
                         group item by (GroupByFunc) into listData
                         select new Grouping<string, SEListItemTemplate>(listData.Key, listData);

If I try this the last line (Select new Grouping.. ) throws a compilation error If I change string to object it compiles fine but then throws an error on runtime saying At least 1 object should implement Icomparable for Ordering & At least one object should implement IGrouping for the grouping part in above query. How can I achieve this?

Just in case needed below is the definition of my custom Sort & Group Funcs

public Func<SEListItemTemplate, Object> OrderByFunc
    {
        get{return _orderByFunc; }
        set {_orderByFunc = value; }
    }

public Func<SEListItemTemplate, Object> OrderByFunc
    {
        get {return _orderByFunc; }
        set {_orderByFunc = value; }
    }

Any help is appreciated. Thanks

1

There are 1 best solutions below

0
On

Update: The following code worked well. Please let me know if there is a better way to write this lambda function below. `

 var sorted = CollPublic.OrderBy(OrderByFunc).GroupBy(GroupByFunc);

                foreach (var item in sorted)
                {
                    var t = new Grouping<object, SEListItemTemplate>(item.Key, item);
                    MonkeysGrouped.Add(t); 
                }  
list.ItemsSource = MonkeysGrouped;