by Guest » 05 Jan 2025, 08:19
Ich schreibe eine Bibliotheksfunktion, um eine Aufzählung in mehrere Aufzählungsbereiche aufzuteilen, stoße jedoch auf ein unerklärliches Problem mit der Enumerator-aus-Linq-Select-Klausel. Bitte sehen Sie sich unten das repräsentative Codebeispiel und die Ausgabe an.
Das riecht nach einem Struktur-Enumerator-Problem, aber ich kann das Problem beim besten Willen nicht genau bestimmen, um es zu umgehen it.
Hilfe wird sehr geschätzt!
Code: Select all
class Program
{
private static IEnumerable wrap(IEnumerable collection)
{
return wrapped();
IEnumerable wrapped()
{
Console.Write($"{collection.Count()} items: ");
using (var etor = collection.GetEnumerator())
{
if (!(etor is object)) throw new Exception();
yield return inner();
IEnumerable inner() { while (etor.MoveNext()) yield return etor.Current; }
}
}
}
static void Main(string[] args)
{
var c1 = Enumerable.Range(0, 5);
var c2 = Enumerable.Range(0, 5).Select(x => x);
var c3 = Enumerable.Range(0, 5).Select(x => x).ToList();
print(wrap(c1).First()); // ok
print(wrap(c2).First()); // empty!
print(wrap(c3).First()); // ok
Console.WriteLine(""); Console.ReadKey();
void print(IEnumerable tt) => Console.Write(string.Join(", ", tt) + "\n");
}
}
Konsolenausgabe:
Code: Select all
5 items: 0, 1, 2, 3, 4
5 items:
5 items: 0, 1, 2, 3, 4
Ich schreibe eine Bibliotheksfunktion, um eine Aufzählung in mehrere Aufzählungsbereiche aufzuteilen, stoße jedoch auf ein unerklärliches Problem mit der Enumerator-aus-Linq-Select-Klausel. Bitte sehen Sie sich unten das repräsentative Codebeispiel und die Ausgabe an.
Das riecht nach einem Struktur-Enumerator-Problem, aber ich kann das Problem beim besten Willen nicht genau bestimmen, um es zu umgehen it.
Hilfe wird sehr geschätzt!
[code]class Program
{
private static IEnumerable wrap(IEnumerable collection)
{
return wrapped();
IEnumerable wrapped()
{
Console.Write($"{collection.Count()} items: ");
using (var etor = collection.GetEnumerator())
{
if (!(etor is object)) throw new Exception();
yield return inner();
IEnumerable inner() { while (etor.MoveNext()) yield return etor.Current; }
}
}
}
static void Main(string[] args)
{
var c1 = Enumerable.Range(0, 5);
var c2 = Enumerable.Range(0, 5).Select(x => x);
var c3 = Enumerable.Range(0, 5).Select(x => x).ToList();
print(wrap(c1).First()); // ok
print(wrap(c2).First()); // empty!
print(wrap(c3).First()); // ok
Console.WriteLine(""); Console.ReadKey();
void print(IEnumerable tt) => Console.Write(string.Join(", ", tt) + "\n");
}
}
[/code]
Konsolenausgabe:
[code]5 items: 0, 1, 2, 3, 4
5 items:
5 items: 0, 1, 2, 3, 4
[/code]