Elliott James Elliott James - 8 days ago 4
C# Question

De-duplicate for each loop c#

I have a foreach loop that returns something like this:

value 1
value 1
value 1
value 2
value 2
value 2
value 2


I need to get that list but only the first of each type. So,

value 1
value 2


below is my code.

<div>
@foreach (var publishedVideo in allVideos)
{
<p>@publishedVideo.GetPropertyValue("segment")</p>
}
</div>


How do I de-duplicate the list?

Answer

Supposing that your class does not implement an equality comparer (hence Distinct wouldn't work), you could use this:

<div>
    @{ 
        var nonDuplicatedVideos = allVideos.
            .Select(x => x.GetPropertyValue("segment"))
            .Distinct();
    }
    @foreach (var publishedVideo in nonDuplicatedVideos)
    {
        <p>@publishedVideo</p>
    }
</div>