我有一个包含两个字符串和一个DateTime的对象的List<>
。我想创建另一个只包含最后一个唯一项目的对象列表,使用两个字符串作为键和最后一个DateTime值。在SQL中,请考虑以下内容:List <>上的递归循环导致计算器溢出
SELECT col1, col2, MAX(datetime) FROM table GROUP BY col1, col2
这给出了col1,col2和最后一个datetime的唯一列表。所以..我试图用两个列表的代码来做到这一点。其中有一个重复项,它解析并抓取最后一个唯一项目以填充第二个列表。
我拥有的数据集非常庞大,只需通过重复列表,然后检查项目是否在唯一列表中,如果它没有添加它,如果是,比较日期等。所以我想我可以通过递归遍历重复列表并获取唯一项目,找到它们的最大日期时间,并在我循环时删除非最大值列表,从而使我的重复列表变得越来越小,从而加快速度。 (我希望你仍然跟着我..)
所以无论如何。我写了一个带有两个列表的递归循环,但是当我循环时,我在第3000次迭代中得到了一个System.StackOverflowException
。
这是我的代码。想象一下ListWithDuplicates
充满了数据。实际的ListDataItem
有更多我遗漏的属性。但我的主要问题是为什么我不能通过这种方式循环通过public list
而不会导致StackOverflowException
?
using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Linq;
public class RecursionTest
{
public List<listDataItem> ListWithDuplicates { get; set; }
public List<listDataItem> ListWithUniques { get; set; }
public RecursionTest()
{
Process();
}
public void Process()
{
int rowcount = 0;
int duplicates = 0;
int total = 0;
RecursiveLoopForUnique(ref rowcount, ref duplicates, ref total, "", "");
}
private void RecursiveLoopForUnique(ref int rowcount, ref int duplicates, ref int total, string col1, string col2)
{
if (rowcount > 0)
duplicates += ListWithDuplicates.RemoveAll(z => z.COL1 == col1 && z.COL2 == col2);
if (ListWithDuplicates.Count > 0)
{
foreach (listDataItem item in ListWithDuplicates)
{
rowcount++;
if (ListWithUniques.FindAll(z => z.COL1 == item.COL1 && z.COL2 == item.COL2).Count < 1)
{
ListWithUniques.Add(ListWithDuplicates.FindAll(z => z.COL1 == item.COL1 && z.COL2 == item.COL2).OrderByDescending(z => z.DATETIME).First());
col1 = item.COL1;
col2 = item.COL2;
break;
}
}
RecursiveLoopForUnique(ref rowcount, ref duplicates, ref total, col1, col2);
}
else
return;
}
public class listDataItem
{
public string COL1 { get; set; }
public string COL2 { get; set; }
public DateTime DATETIME { get; set; }
public listDataItem(string col1, string col2, DateTime datetime)
{
COL1 = col1;
COL2 = col2;
DATETIME = datetime;
}
}
}
是否有可能在没有'break'的情况下重新编写它,并且空'return'?这听起来像是在寻求麻烦。 – FrustratedWithFormsDesigner 2010-08-20 21:00:00
@FrustratedWithFormsDesigner - 你是对的。好点子。我添加了额外的if语句,因为我得到了溢出异常。我也不需要将col值传递回递归函数,并且可以在退出foreach后删除它们。我试图超过这个例外的函数搞砸了。没有麻烦;-) – craigpj 2010-08-24 09:39:56