makz
makz

Reputation: 97

How to take only one element from foreach loop

I have a problem, the code will display each item from the list, however, the user can delete only his own like. How can I improve the code so only one element from the list is displayed?

Any help is appreciated. Thank you!

cshtml:

@if (User.Identity.IsAuthenticated)
{
    @if (Model.MovieDetail.Likes.Any(x => x.UserId == (int.Parse(User.FindFirst("Id").Value))))
    {
        @foreach (var like in Model.MovieDetail.Likes)
        {
            @if (Model.MovieDetail.Likes.Any(x => x.UserId == like.UserId))
            {
                <a asp-controller="Likes" asp-action="Remove" asp-route-id="@like.Id"><div><i class="fas fa-heart fa-2x" style="color:red;"></i><span style="color:red;"> @Convert.ToInt32(Model.MovieDetail.Likes.Count) </span></div></a>
            }
        }
    }
    @if (Model.MovieDetail.Likes.All(x => x.UserId != (int.Parse(User.FindFirst("Id").Value))))
    {
        <a asp-controller="Likes" asp-action="Add" asp-route-id="@Model.MovieDetail.Id"><div id="the_heart"><i class="far fa-heart fa-2x" style="color:red;"></i><span style="color:red;">@Convert.ToInt32(Model.MovieDetail.Likes.Count)</span></div></a>
    }
}

enter image description here

Upvotes: 0

Views: 275

Answers (1)

Geoduck
Geoduck

Reputation: 8995

@if (User.Identity.IsAuthenticated)
{
    var like = Model.MovieDetail.Likes.FirstOrDefault(x => x.UserId == (int.Parse(User.FindFirst("Id").Value)));
    if (like != null)
    {
        <a asp-controller="Likes" asp-action="Remove" asp-route-id="@like.Id"><div><i class="fas fa-heart fa-2x" style="color:red;"></i><span style="color:red;"> @Convert.ToInt32(Model.MovieDetail.Likes.Count) </span></div></a>
    }
    else
    {
        <a asp-controller="Likes" asp-action="Add" asp-route-id="@Model.MovieDetail.Id"><div id="the_heart"><i class="far fa-heart fa-2x" style="color:red;"></i><span style="color:red;">@Convert.ToInt32(Model.MovieDetail.Likes.Count)</span></div></a>
    }
}

Running .Any to find a match on username is exactly the opposite of running .All that don't match. You don't need to test it twice, let alone n + 2 times as you were doing.

Upvotes: 1

Related Questions