[Tex/LaTex] Macro to access a specific member of a list

foreachtikz-pgf

I want to be able to have a macro access a specific element of a list. The following code works, however requires me to have two separate macros: one that accepts a list, and the other that accepts the name of a macro that contains the list.

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{xstring}

\begin{document}

\newcommand*{\GetListMemberA}[2]{%
\foreach \a [count=\i] in {#1} {%
\IfEq{\i}{#2}{\a\breakforeach}{}%
}%
\par%
}%

% This is same as above except does not have {} around #1
\newcommand*{\GetListMemberB}[2]{%
\foreach \a [count=\i] in #1 {%
\IfEq{\i}{#2}{\a\breakforeach}{}%
}%
\par%
}%

\newcommand*{\MyList}{a1,b2,c3,d4,e5}%

% These work if the foreach uses {#1} (ie, with the curly braces)
This should print "b": \GetListMemberA{a,b,c,d,e}{2}%
This should be blank: \GetListMemberA{a,b,c,d,e}{6}%

% These work if the foreach uses #1 (ie, without the curly braces}
This should be "a1": \GetListMemberB{\MyList}{1}%
This should be "c3": \GetListMemberB{\MyList}{3}%
This should be blank: \GetListMemberB{\MyList}{6}%

\end{document}


This question on TikZ \foreach loop with macro-defined list suggest to remove the braces around the macro when using a foreach, and that is how I was able to come up with this solution.

So, how can I change this so I don't have to have two macros?

I don't think this issue is related to Using Macro Defined Lists in TikZ/PGFplots as that was specific to lists used to label tick marks on axis.

To make the macro work both with inline lists and with lists in macros, you can use \edef to assemble the loop command, with \noexpand before every macro except for the arguments:

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{xstring}

\begin{document}

% This works both with inline lists and with macros containing lists
\newcommand*{\GetListMember}[2]{%
\edef\dotheloop{%
\noexpand\foreach \noexpand\a [count=\noexpand\i] in {#1} {%
\noexpand\IfEq{\noexpand\i}{#2}{\noexpand\a\noexpand\breakforeach}{}%
}}%
\dotheloop
\par%
}%

\newcommand*{\MyList}{a1,b2,c3,d4,e5}%

This should print "b": \GetListMember{a,b,c,d,e}{2}%
This should be blank: \GetListMember{a,b,c,d,e}{6}%

This should be "a1": \GetListMember{\MyList}{1}%
This should be "c3": \GetListMember{\MyList}{3}%
This should be blank: \GetListMember{\MyList}{6}%

\end{document}