使用 tabular 和 foreach 以及 csname 绘制一行

使用 tabular 和 foreach 以及 csname 绘制一行

\foreach我想使用和根据所选条目有条件地向表中添加一行\csname...\endcsname。但是它不起作用。

\documentclass{article}

\usepackage{tikz}
\usepackage{pdftexcmds}

\newcommand{\UserA}{UserA}
\newcommand{\UserB}{UserB}
\newcommand{\UserZ}{UserZ}
\newcommand{\UserIdx}{B}

\newcommand{\test}{%
  \def\temp{}%
  \foreach \Idx in {A,...,Z}{%
        \ifcsname User\Idx \endcsname%
            \ifnum\pdfstrcmp{\Idx}{\UserIdx}=0%
                %\expandafter\gdef\expandafter\temp\expandafter{\temp t1 & t2 \\}% % Works
                \expandafter\gdef\expandafter\temp\expandafter{\temp \csname User\Idx \endcsname & C21 \\}% % Does not work
            \fi
        \fi
  }%
    \temp}

\begin{document}

\begin{tabular}{ll}
    \test
    C12 & C22
\end{tabular}

\end{document}

答案1

您需要额外的扩展:

\expandafter\expandafter\expandafter
  \gdef\expandafter\expandafter\expandafter
  \temp\expandafter\expandafter\expandafter{\temp \csname User\Idx \endcsname & C21 \\}% % Works

但是,以下内容可能更直观:

在此处输入图片描述

\documentclass{article}

\usepackage{pgffor}

\newcommand{\UserA}{UserA}
\newcommand{\UserB}{UserB}
\newcommand{\UserZ}{UserZ}
\newcommand{\UserIdx}{B}

\newcommand{\test}{%
  \def\temp{}%
  \foreach \Idx in {A,...,Z}{%
    \ifcsname User\Idx \endcsname
      \ifnum\pdfstrcmp{\Idx}{\UserIdx}=0
        %\expandafter\gdef\expandafter\temp\expandafter{\temp t1 & t2 \\}% % Works
        %\expandafter\gdef\expandafter\temp\expandafter{\temp \csname User\Idx \endcsname & C21 \\}% % Does not work
        \edef\x{\csname User\Idx\endcsname}%
        \xdef\temp{\temp \x & C21 \noexpand\\}% % Works
      \fi
    \fi
  }%
  \temp}

\begin{document}

\begin{tabular}{ll}
  \test
  C12 & C22
\end{tabular}

\end{document}

相关内容