gpt4 book ai didi

c# - 如何递归遍历嵌套泛型集合?

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:03 25 4
gpt4 key购买 nike

我想计算嵌套集合中类的数量,例如[[[1,2],[3,4,5]],[[1,2],[3,4,5]]]。这里引用的类是“int”,预期答案是 10。

我将此列表生成为:

        List<int> list1 = new List<int>(2);
list1.Add(1);
list1.Add(2);
List<int> list2 = new List<int>(3);
list2.Add(3);
list2.Add(4);
list2.Add(5);

List<List<int>> listlist = new List<List<int>>(2);
listlist.Add(list1);
listlist.Add(list2);

List<List<List<int>>> listlistlist = new List<List<List<int>>>(2);
listlistlist.Add(listlist);
listlistlist.Add(listlist);

我在编程的时候,比较喜欢为泛型类写这样的方法,我的代码是:

    public static int CountT<T>(ICollection<T> pTCol, int intLevel = 1)
{
int intCount = 0;
if (intLevel > 0)
{
intLevel--;
foreach (T pT in pTCol)
{
ICollection<T> subTCol = pT as ICollection<T>; //PROBLEM: I got "null" for subTCol when the program was running
intCount += CountT(subTCol, intLevel);
}
}
else if (intLevel == 0)
{
intCount = pTCol.Count;
}
return intCount;
}

我测试了上面的代码

        int intCount = CountT(listlistlist, 2);

然后我遇到了问题

        ICollection<T> subTCol = pT as ICollection<T>;   //PROBLEM: I got "null" for subTCol when the program was running

我也试过代码:

    public static int CountT2<T, T2>(ICollection<T> pTCol, int intLevel = 1)
{
int intCount = 0;
if (intLevel > 0)
{
intLevel--;
foreach (T pT in pTCol)
{
ICollection<T2> subTCol = pT as ICollection<T2>;
intCount += CountT2(subTCol, intLevel); //PROBLEM: The type arguments for method cannot be inferred from the usage. Try specifying the type arguments explicitly. (I could not pass the compiling)
}
}
else if (intLevel == 0)
{
intCount = pTCol.Count;
}
return intCount;
}

编译不通过

        intCount += CountT2(subTCol, intLevel);   //PROBLEM: The type arguments for method cannot be inferred from the usage. Try specifying the type arguments explicitly. (I could not pass the compiling)

我该怎么做?

最佳答案

ICollection subTCol = pT as ICollection//问题:我的 subTCol 为“null”

这是 null 的原因是 pT不是 ICollection<T>因为TintlistlistlistList<List<List<T>>> .因此pTList<List<T>>这就是为什么如果您尝试将其转换为 ICollection<T>你会得到空值。

我想计算嵌套集合中的项目数。

使用 可以更轻松地做到这一点的 Sum方法。如果您知道嵌套级别,例如:

Assert.AreEqual(10, listlistlist.Sum(x => x.Sum(y => y.Count)));

如果您不知道嵌套级别或者您想要一个更通用的方法,您可以创建一个扩展方法,例如:

public static class RecursiveSumExtension
{
public static int RecursiveSum(this IEnumerable items)
{
if (null == items)
return 0;

var total = 0;

foreach (var item in items)
{
if (item is IEnumerable)
total += (item as IEnumerable).RecursiveSum();

else
total++;
}

return total;
}
}

和测试:

 Assert.AreEqual(10, listlistlist.RecursiveSum());

列表生成

顺便说一句,您可以使用 的集合初始化器语法使代码在创建集合时更具可读性:

        var listlist = new List<List<int>>
{
new List<int> {1, 2},
new List<int> {3, 4, 5}
};

var listlistlist = new List<List<List<int>>>
{
listlist,
listlist
};

关于c# - 如何递归遍历嵌套泛型集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25741746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com