LINQ는 LIFO 순서로 스택을 반복합니다.

Dec 08 2020

LINQ 메서드 가 LIFO (Last In, First Out) 순서 로 Stack 의 내용을 반복 합니까 (그리고 내 특정 경우 Stack ). 스택으로 밀어 넣었습니다). 또한 부작용이 없으므로 반복하는 동안 스택이 터지는 것을 피할 수 있습니까?

간단한 질문입니다. 예와 예라고 가정하겠습니다.하지만 검색이 너무 간단해서 많은 양의 LINQ 및 Stack 관련 답변이 생성되었으며, 검색 한 수많은 결과가이 사례에 구체적으로 답변하지 않았습니다.

답변

1 AndrewH Dec 08 2020 at 17:24

예.

다음 실험은 스택의 LIFO 순서를 따른다는 것을 보여줍니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class DoesLinqIterateAStackInLifo
{
    public static void Main()
    {
        var stack = new Stack<char>();
        stack.Push('s');
        stack.Push('e');
        stack.Push('Y');
        Console.WriteLine(stack.Aggregate(new StringBuilder(), (builder,letter) => builder.Append(letter)));
        Console.WriteLine(string.Join("",stack.ToList()));      
        if(stack.Count==3) 
        {
            Console.WriteLine("And it will not pop the stack");
        }       
    }
}

산출:

Yes
Yes
And it will not pop the stack