5. In the Cartesian coordinate system $x O y$, 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} 、 y_{i} \leqslant n$ ( $n$ is an integer). If there are 516 such triangles, then the value of $n$ is ( ).
(A) 3
(B) 4
(C) 5
(D) 6
5.B.

It is known that when $n \geqslant 5$, the number of triangles exceeds 516. Therefore, we only need to consider the case where $n \leqslant 4$. In this case, all sets of three points total $\mathrm{C}_{n}^{3_{2}}$.

Among these, the sets of three points that cannot form a triangle include: sets of three collinear points in the horizontal or vertical direction, totaling $2 n \mathrm{C}_{n}^{3}$; sets of three collinear points in the direction with a slope of $\pm 1$, totaling $2\left(\mathrm{C}_{n}^{3}+2 \mathrm{C}_{n-1}^{3}+2 \mathrm{C}_{n-2}^{3}+\cdots+2 \mathrm{C}_{3}^{3}\right)$. Thus,
$$
\mathrm{C}_{n}^{3}-2 n \mathrm{C}_{n}^{3}-2\left(\mathrm{C}_{n}^{3}+2 \mathrm{C}_{n-1}^{3}+2 \mathrm{C}_{n-2}^{3} \cdots+2 \mathrm{C}_{3}^{3}\right)=516 \text {. }
$$

Substituting $n=2,3,4$ into the above equation, we get $n=4$.