2

I want to add a row to a table conditionally based on the selected entry, using \foreach and \csname...\endcsname. But it is not working.

\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}
2

You need an additional expansion:

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

However, the following might be more intuitive:

enter image description here

\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}
  • I knew that should be something like this. But \expandafter is always tricky for me. Is there a simpler way to achieve the same result? – cacamailg Nov 5 '16 at 1:39
  • What if the \csname...\endcsame is in the first column? – cacamailg Nov 5 '16 at 1:58
  • 1
    @cacamailg: Try \edef\x{\csname User\Idx\endcsname}% \xdef\temp{\temp \x & C21 \noexpand\\}%. – Werner Nov 5 '16 at 2:22
  • @cacamailg: Done. – Werner Nov 5 '16 at 2:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.