0

我有一个从 fetchXML 查询中填充的列表,但不幸的是它返回了很多带有重复标题的事件。因此,作为一种解决方案,我希望遍历列表中的每个项目,如果标题与前一个项目相同,那么我想将 item.YearId 和 item.Year 中的值添加到年份列表中在先前循环的项目中。

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;
}

因此,Event 类包含一个 Year 列表属性,该属性由一个 guid (item.YearId) 和一个 int (item.Year) 组成。

希望这是有道理的。任何例子都会很棒。谢谢你。

4

3 回答 3

0

我认为从 xml 获取项目时应该使用分组。类似的东西(只是一个示例,因为我不知道你的 xml 看起来如何):

var result = from p in fetchResults.Root.Elements("result")
             group p by p.Name into g
             select new Foo { 
                  Name = g.Key, 
                  Years = g.Select(x => (int)x.Element("year")).ToList()
             };
于 2013-02-06T13:49:47.197 回答
0

创建对前一项的引用并使用该引用,以便您的代码变为

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;

//Reference to previous event
Event previousEvent = null;

foreach (var item in result)
{
    if (item.Name == previousTitle && previousEvent != null)
    {
        //Add to the previous event
        previousEvent.yearList.Add(item.Year);
        previousEvent.yearIdList.Add(item.YearId);
    }
    else
    {
        //otherwise add who item to eventDetails list.
        eventDetails.Add(item);
    }

    previousTitle = item.Name;
    previousEvent = item;
}
于 2013-02-06T13:53:25.600 回答
0

你可以使用这样的东西。我不知道你的事件对象是什么样的,但你应该明白。

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;
    }
}
于 2013-02-06T13:55:19.703 回答