LINQ Group-by with complete object access

c#, linq

Solution

Why not just include the serial number as part of the key via the anonymous type you're declaring:

var items = context.Items.GroupBy(g => new {g.Name, g.Model, g.SerialNumber })
            .Where(/*...*/) 
            .Select(i => new ItemModel {
                    Name=g.Key.Name,
                    SerialNumber = g.FirstOrDefault().SerialNumber //<-- here
             });

Or, alternatively, make your object the key:

var items = context.Items.Where(...).GroupBy(g => g)
    .Select(i => new ItemModel {...});

Sometimes it can be easier to comprehend the query syntax (here, I've projected the `Item` object as part of the key):

var items = from i in context.Items
            group i by new { Serial = g.Serialnumber, Item = g } into gi
            where /* gi.Key.Item.GetType() == typeof(context.Items[0]) */
            select new ItemModel { 
                 Name = gi.Key.Name, 
                 SerialNumber = gi.Key.Serial 
                 /*...*/ 
            };

EDIT: you could try grouping after projection like so:

var items = context.Items.Where(/*...*/).Select(i => new ItemModel { /*...*/})
    .GroupBy(g => new { g.Name, g.Model });

you get an `IGrouping<AnonymousType``1, IEnumerable<ItemModel>>` from this with your arbitrary `group by` as the key, and your ItemModels as the grouped collection.

Problem

What I want is better explained with code. I have this query: ``` var items = context.Items.GroupBy(g => new {g.Name, g.Model}) .Where(/*...*/) .Select(i => new ItemModel{ Name=g.Key.Name, SerialNumber = g.FirstOrDefault().SerialNumber //<-- here }); ``` Is there a better way to get the serial number or some other property that is not used in the key? The only way I could think of is to use FirstOrDefault.

Original source