Q:

Is there a better way to set a property common to a list of items in linq

I have the following class:
public class Vehicle
{
    public string Make { get; set; }
    public DateTime DateManufactured { get; set; }
}

I then made a list of vehicles like:
        var dateTime1 = DateTime.Now.AddDays(-7);
        var dateTime2 = DateTime.Now.AddDays(-8);
        var dateTime3 = DateTime.Now.AddDays(-9);

        var vehicles = new List<Vehicle>
            {
                new Vehicle {Make = "Ferrari", DateManufactured = dateTime1},
                new Vehicle {Make = "Mazda", DateManufactured = dateTime2},
                new Vehicle {Make = "Dodge", DateManufactured = dateTime3},
                new Vehicle {Make = "Holden", DateManufactured = dateTime1},
                new Vehicle {Make = "Chrysler", DateManufactured = dateTime2},
                new Vehicle {Make = "Mazda", DateManufactured = dateTime3},
            };

Next I was trying to get a list of DatesManufactured and for each date the vehicles that were manufactured on that date.
So I went for:
var vehiclesGroupedByDate = vechicles.GroupBy(x => x.DateManufactured)
                .Select(x => new
                    {
                        x.First().DateManufactured,
                        Vehicles = x.ToList()
                    });

This works fines but I'm not sure about the x.First() part. It works but it doesn't feel quite right. Does anybody know of a more elegant way to code this?

A:

When you use GroupBy, it will create an IGrouping<TKey, TItem>, so you can simply do the following:
var vehiclesGroupedByDate = vechicles.GroupBy(x => x.DateManufactured)
            .Select(x => new
                {
                    x.Key,
                    Vehicles = x.ToList()
                });

A:

I don't see anything wrong with your code, but you can also use x.Key instead of x.First().DateManufactured which wouldn't require a creation of an another IEnumerable.

A:

GroupBy exposes a Key property:
var vehiclesGroupedByDate = vechicles.GroupBy(x => x.DateManufactured)
    .Select(x => new
    {
        x.Key,
        Vehicles = x.ToList()
    });

