gpt4 book ai didi

.net - 如何同时迭代多个 IEnumerables

转载 作者:行者123 更新时间:2023-12-04 20:22:28 24 4
gpt4 key购买 nike

假设我有两个(或更多)IEnumerable<T>有很多元素。每IEnumerable有另一种类型 T .列表可能非常长,不应完全加载到内存中。

IEnumerable<int> ints = getManyInts();
IEnumerable<string> strings = getSomeStrings();
IEnumerable<DateTime> dates = getSomeDates();

我想要做的是遍历这些列表,并为每一步获取一个包含一个 int、一个字符串和一个 DateTime 的项目,直到到达最长或最短列表的末尾。应该支持这两种情况(bool 参数最长与最短左右)。对于较短列表中不可用的每个项目(因为已经结束),我希望使用默认值。
for(Tuple<int,string,DateTime> item in 
Foo.Combine<int,string,DateTime>(ints, strings, dates))
{
int i=item.Item1;
string s=item.Item2;
DateTime d=item.Item3;
}

是否可以使用延迟执行在 linq 中做到这一点?
我知道使用 IEnumerators 直接结合 yield 返回的解决方案。
How can I iterate over two IEnumerables simultaneously in .NET 2

最佳答案

应该这样做(警告-未经测试):

public static IEnumerable<Tuple<T, U, V>> IterateAll<T, U, V>(IEnumerable<T> seq1, IEnumerable<U> seq2, IEnumerable<V> seq3)
{
bool ContinueFlag = true;
using (var e1 = seq1.GetEnumerator())
using (var e2 = seq2.GetEnumerator())
using (var e3 = seq3.GetEnumerator())
{
do
{
bool c1 = e1.MoveNext();
bool c2 = e2.MoveNext();
bool c3 = e3.MoveNext();
ContinueFlag = c1 || c2 || c3;

if (ContinueFlag)
yield return new Tuple<T, U, V>(c1 ? e1.Current : default(T), c2 ? e2.Current : default(U), c3 ? e3.Current : default(V));
} while (ContinueFlag);
}
}

关于.net - 如何同时迭代多个 IEnumerables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4888593/

24 4 0