I was wondering if anyone knows how to tell Beamer to divide the table of contents in the headline in columns if there are too many sections, else leave it in one column.

I found this thread very useful

Beamer with Warsaw Theme: Two column navigation

However, with this code, the ToC will always show up in two columns, which is not always esthetically pleasing (when there are only 2 sections, for example).

I am working on a customized template for my institution, which is why I need to make it as versatile as possible.

I was thinking of something along the lines of keeping the default \insertsectionnavigation if the height of the table of contents is smaller than or equal to the height of the headline, else divide. But I am having trouble turning this into proper code.

Easiest solution is probably to check the total number of sections. If this number is bigger then same value (5 in the example) your custom code is shown, else the normal navigation.

[insert your custom code at "whatever theme you want"]

\documentclass{beamer}
\usetheme{Warsaw}

\makeatletter
\leavevmode%
\@tempdimb=2.4375ex%
\ifnum\beamer@subsectionmax<\beamer@sectionmax%
\multiply\@tempdimb by\beamer@sectionmax%
\else%
\multiply\@tempdimb by\beamer@subsectionmax%
\fi%
\ifdim\@tempdimb>0pt%
\vbox to\@tempdimb{\vfil%
\ifnum\beamer@sectionmax<5
\else%
whatever theme you want
\fi%
\vfil}%
\end{beamercolorbox}%
\end{beamercolorbox}%
\fi%
}
\makeatother

\begin{document}

\section{a}\frame{a}
\section{a}\frame{a}
\section{a}\frame{a}
\section{a}\frame{a}
\section{a}\frame{a}
\section{a}\frame{a}
\section{a}\frame{a}
\section{a}\frame{a}
\section{a}\frame{a}
\section{a}\frame{a}

\end{document}