Q:

Adding value to list within list

I have a list that has been populated from a fetchXML query, but unfortunately it is returning a lot of events with duplicate titles. So as a solution i'm hoping to loop through each item in the list and, if the title is the same as the previous item, then I would like to add the values from item.YearId & item.Year to a list of years within the previously looped item.
var result = from p in fetchResults.Root.Elements("result") ... //etc

//Creating another list to contain desired results.
List<Event> eventDetails = new List<Event>();

//Create to store the previously looped title.
string previousTitle = string.Empty;

foreach (var item in result)
{
    if (item.Name == previousTitle)
    {
        //Not sure how to add item.yearId and item.Year to a Year
        //list inside the previously looped.
    }
    else
    {
        //otherwise add who item to eventDetails list.
        eventDetails.Add(item);
    }

    previousTitle = item.Name;
}

So, the Event class contains a Year list property that which consists of a guid (item.YearId) and an int (item.Year).
Hope that this makes sense.  Any examples would be great.  Thank you.

A:

You could use something like this. I dont know what your event object looks like, but you should get the idea.
List<Event> eventDetails = new List<Event>();
Event lastEvent = null;

foreach (var item in result)
{
    if ((lastEvent != null) && (lastEvent.Name == item.Name))
    {
        lastEvent.AddYearAndYearId(item.Year, item.YearId);
        eventDetails[eventDetails.Count - 1] = lastEvent;
    }
    else
    {
        eventDetails.Add(item);
        lastEvent = item;
    }
}

