def to_stacked_array(
        self,
        new_dim: Hashable,
        sample_dims: Collection[Hashable],
        variable_dim: Hashable = "variable",
        name: Hashable | None = None,
    ) -> DataArray:
        """Combine variables of differing dimensionality into a DataArray
        without broadcasting.

        This method is similar to Dataset.to_dataarray but does not broadcast the
        variables.

        Parameters
        ----------
        new_dim : hashable
            Name of the new stacked coordinate
        sample_dims : Collection of hashables
            List of dimensions that **will not** be stacked. Each array in the
            dataset must share these dimensions. For machine learning
            applications, these define the dimensions over which samples are
            drawn.
        variable_dim : hashable, default: "variable"
            Name of the level in the stacked coordinate which corresponds to
            the variables.
        name : hashable, optional
            Name of the new data array.

        Returns
        -------
        stacked : DataArray
            DataArray with the specified dimensions and data variables
            stacked together. The stacked coordinate is named ``new_dim``
            and represented by a MultiIndex object with a level containing the
            data variable names. The name of this level is controlled using
            the ``variable_dim`` argument.

        See Also
        --------
        Dataset.to_dataarray
        Dataset.stack
        DataArray.to_unstacked_dataset

        Examples
        --------
        >>> data = xr.Dataset(
        ...     data_vars={
        ...         "a": (("x", "y"), [[0, 1, 2], [3, 4, 5]]),
        ...         "b": ("x", [6, 7]),
        ...     },
        ...     coords={"y": ["u", "v", "w"]},
        ... )

        >>> data
        <xarray.Dataset> Size: 76B
        Dimensions:  (x: 2, y: 3)
        Coordinates:
          * y        (y) <U1 12B 'u' 'v' 'w'
        Dimensions without coordinates: x
        Data variables:
            a        (x, y) int64 48B 0 1 2 3 4 5
            b        (x) int64 16B 6 7

        >>> data.to_stacked_array("z", sample_dims=["x"])
        <xarray.DataArray 'a' (x: 2, z: 4)> Size: 64B
        array([[0, 1, 2, 6],
               [3, 4, 5, 7]])
        Coordinates:
          * z         (z) object 32B MultiIndex
          * variable  (z) <U1 16B 'a' 'a' 'a' 'b'
          * y         (z) object 32B 'u' 'v' 'w' nan
        Dimensions without coordinates: x

        """
        from xarray.structure.concat import concat

        # add stacking dims by order of appearance
        stacking_dims_list: list[Hashable] = []
        for da in self.data_vars.values():
            for dim in da.dims:
                if dim not in sample_dims and dim not in stacking_dims_list:
                    stacking_dims_list.append(dim)
        stacking_dims = tuple(stacking_dims_list)

        for key, da in self.data_vars.items():
            missing_sample_dims = set(sample_dims) - set(da.dims)
            if missing_sample_dims:
                raise ValueError(
                    "Variables in the dataset must contain all ``sample_dims`` "
                    f"({sample_dims!r}) but '{key}' misses {sorted(map(str, missing_sample_dims))}"
                )

        def stack_dataarray(da):
            # add missing dims/ coords and the name of the variable

            missing_stack_coords = {variable_dim: da.name}
            for dim in set(stacking_dims) - set(da.dims):
                missing_stack_coords[dim] = None

            missing_stack_dims = list(missing_stack_coords)

            return (
                da.assign_coords(**missing_stack_coords)
                .expand_dims(missing_stack_dims)
                .stack({new_dim: (variable_dim,) + stacking_dims})
            )

        # concatenate the arrays
        stackable_vars = [stack_dataarray(da) for da in self.data_vars.values()]
        data_array = concat(stackable_vars, dim=new_dim)

        if name is not None:
            data_array.name = name

        return data_array
Combine variables of differing dimensionality into a DataArray
        without broadcasting.

        This method is similar to Dataset.to_dataarray but does not broadcast the
        variables.

        Parameters
        ----------
        new_dim : hashable
            Name of the new stacked coordinate
        sample_dims : Collection of hashables
            List of dimensions that **will not** be stacked. Each array in the
            dataset must share these dimensions. For machine learning
            applications, these define the dimensions over which samples are
            drawn.
        variable_dim : hashable, default: "variable"
            Name of the level in the stacked coordinate which corresponds to
            the variables.
        name : hashable, optional
            Name of the new data array.

        Returns
        -------
        stacked : DataArray
            DataArray with the specified dimensions and data variables
            stacked together. The stacked coordinate is named ``new_dim``
            and represented by a MultiIndex object with a level containing the
            data variable names. The name of this level is controlled using
            the ``variable_dim`` argument.

        See Also
        --------
        Dataset.to_dataarray
        Dataset.stack
        DataArray.to_unstacked_dataset

        Examples
        --------
        >>> data = xr.Dataset(
        ...     data_vars={
        ...         "a": (("x", "y"), [[0, 1, 2], [3, 4, 5]]),
        ...         "b": ("x", [6, 7]),
        ...     },
        ...     coords={"y": ["u", "v", "w"]},
        ... )

        >>> data
        <xarray.Dataset> Size: 76B
        Dimensions:  (x: 2, y: 3)
        Coordinates:
          * y        (y) <U1 12B 'u' 'v' 'w'
        Dimensions without coordinates: x
        Data variables:
            a        (x, y) int64 48B 0 1 2 3 4 5
            b        (x) int64 16B 6 7

        >>> data.to_stacked_array("z", sample_dims=["x"])
        <xarray.DataArray 'a' (x: 2, z: 4)> Size: 64B
        array([[0, 1, 2, 6],
               [3, 4, 5, 7]])
        Coordinates:
          * z         (z) object 32B MultiIndex
          * variable  (z) <U1 16B 'a' 'a' 'a' 'b'
          * y         (z) object 32B 'u' 'v' 'w' nan
        Dimensions without coordinates: x

        
xarray/core/dataset.py