gpt4 book ai didi

c# IEnumerable 双重迭代

转载 作者:太空狗 更新时间:2023-10-30 01:07:03 25 4
gpt4 key购买 nike

出于好奇我想问这个问题...

这是我的代码:

for (int i = 0; i < myList.Count - 1; ++i)
{
for (int j = i+1; j < myList.Count; ++j)
{
DoMyStuff(myList[i], myList[j]);
}
}

非常简单的循环,但显然它只适用于 List...但我想知道......我如何编写这个循环以使其独立于集合的类型(从 IEnumerable 派生......)我的第一个想法:

IEnumerator it1 = myList.GetEnumerator();
while (it1.MoveNext())
{
IEnumerator it2 = it1; // this part is obviously wrong
while (it2.MoveNext())
{
DoMyStuff(it1.Current, it2.Current);
}
}

最佳答案

因为枚举器没有获取第 n 个元素的有效方法,所以最好的办法是将可枚举项复制到列表中,然后使用现有代码:

void CrossMap<T>(IEnumerable<T> enumerable)
{
List<T> myList = enumerable.ToList();

for (int i = 0; i < myList.Count - 1; ++i)
{
for (int j = i+1; j < myList.Count; ++j)
{
DoMyStuff(myList[i], myList[j]);
}
}
}

但是,对于某些集合类型,您可以采取相当棘手的技巧。由于 BCL 中某些集合类型的枚举数被声明为值类型,而不是引用类型,因此您可以通过将枚举数复制到另一个变量来创建枚举数状态的隐式克隆:

// notice the struct constraint!
void CrossMap<TEnum, T>(TEnum enumerator) where TEnum : struct, IEnumerator<T>
{
while (enumerator.MoveNext())
{
TEnum enum2 = enumerator; // value type, so this makes an implicit clone!
while (enum2.MoveNext())
{
DoMyStuff(enumerator.Current, enum2.Current);
}
}
}

// to use (you have to specify the type args exactly)
List<int> list = Enumerable.Range(0, 10).ToList();
CrossMap<List<int>.Enumerator, int>(list.GetEnumerator());

这非常迟钝,而且很难使用,所以只有在性能和空间关键的情况下才应该这样做。

关于c# IEnumerable 双重迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13703637/

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