5. On the $x O y$ plane, the coordinates of the vertices of a triangle are $\left(x_{i}, y_{i}\right)(i=1,2,3)$, where $x_{i}, y_{i}$ are integers and satisfy $1 \leqslant x_{i} \leqslant n, 1 \leqslant y_{i} \leqslant n$ ($n$ is an integer), and there are 516 such triangles. Then the value of $n$ is ( ).
(A) 3
(B) 4
(C) 5
(D) 6
5. B.

It is easy to calculate that when $n \geqslant 5$, the number of triangles all exceed 516. Therefore, we only need to consider the case where $n<5$: At this point, all sets of three points have $\mathrm{C}_{n}^{3}$ 2 sets, among which, the sets of three collinear points in the horizontal or vertical direction total $2 n \mathrm{C}_{\mathrm{n}}^{3}$ sets, and the sets of three collinear points in the direction with a slope of $\pm 1$ total $2\left(\mathrm{C}_{n}^{3}+2 \mathrm{C}_{n-1}^{3}+\cdots+2 \mathrm{C}_{3}^{3}\right)$ sets. Hence,
$$
\mathrm{C}_{n}^{3}-2 n \mathrm{C}_{n}^{3}-2\left(\mathrm{C}_{n}^{3}+2 \mathrm{C}_{n-1}^{3}+\cdots+2 \mathrm{C}_{3}^{3}\right)=516 \text {. }
$$

But $C_{3}^{3}+C_{4}^{3}+\cdots+C_{n-1}^{3}=C_{n}^{4}$, so
$$
C_{n}^{3}-2 n C_{n}^{3}-2 C_{n}^{3}-4 C_{n}^{4}=516 \text {. }
$$

Directly trying gives $n=4$.