-1

I try to group by StringId and then by Name

var a = myList
                .GroupBy(item => new TcGroupByKey() 
{StringId = item.Id, ChannelName = item.ChannelName}).ToList();

I have created this inner class TcGroupByKey

so I can pass the result to TrackingChannelRow ctor

and will get strongly type argument and not object

 public TrackingChannelRow(ManageTcModel.TcGroupByKey tcGroupByKey,
            IGrouping<ManageTcModel.TcGroupByKey, TrackingChannelItem> subChannels,
            IEnumerable<Manager.TrackingChannels.Model.ToolbarItem> toolbars,
        IEnumerable<Manager.TrackingChannels.Model.BundleItem> bundles)
        {

But the group by doesn't work.

What am I doing wrong?

2
  • 2
    We've no idea what error you're getting... a short but complete example would be really helpful. Note that GroupBy will only work if your type overrides Equals and GetHashCode appropriately. Maybe that's the problem? Commented Apr 8, 2012 at 14:56
  • 1
    What are you expecting to get? Your query returns a list of group objects, with TcGroupByKey objects serving as keys. Is that not what you expected? Commented Apr 8, 2012 at 14:59

2 Answers 2

0

I think that what you're looking for is to group by composite key...

Something similar to what Marc described in this post Linq to SQL with Group by

The key is to use 'anonymous' types - not the named one like you did - that LINQ can translate into SQL, otherwise there's an issue and that code can only run 'post SQL' (so you enumerate first then group but lose on the SQL integration, performance).

So, in your case it'd be something like this...

new {StringId = item.Id, ChannelName = item.ChannelName}

...instead of new TcGroupByKey() {StringId = item.Id, ChannelName = item.ChannelName}

There is similar problem with doing a 'Select' into anonymous (works) or named type (doesn't - unless, as I mentioned above, you separate the SQL and C#-only expressions part, a bit simplified).

hope this helps

Sign up to request clarification or add additional context in comments.

Comments

0

You are asking linq to group your list by an object he doesn't recognize.

What's wrong with:

var a = myList.GroupBy(Id).GroupBy(ChannelName).ToList();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.