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}

1 Answer 1

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}
4
  • 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, 2016 at 1:39
  • What if the \csname...\endcsame is in the first column?
    – cacamailg
    Nov 5, 2016 at 1:58
  • 1
    @cacamailg: Try \edef\x{\csname User\Idx\endcsname}% \xdef\temp{\temp \x & C21 \noexpand\\}%.
    – Werner
    Nov 5, 2016 at 2:22
  • @cacamailg: Done.
    – Werner
    Nov 5, 2016 at 2:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .