-1

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?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Elliott James
  • 165
  • 14
  • 3
    `allVideos.Distinct()` perhaps? (If your videos implement equality appropriately...) – Jon Skeet Jul 17 '17 at 12:46
  • 1
    `De-duplicate for each loop c# [duplicate]` I love this title. – Flater Jul 17 '17 at 12:51
  • @Flater In Soviet Russia, questions about duplication duplicates you. – silkfire Jul 17 '17 at 12:55
  • @Flater thanks guys, but having already tried the supposed duplicate question, it didn't work. If I understood the answer I wouldn't have asked the question. – Elliott James Jul 17 '17 at 12:58
  • What output did you get when you tried Camilo's solution? – mjwills Jul 17 '17 at 12:59
  • 1
    Try `@foreach(var seg in allVideos.Select(a => a.GetPropertyValue("segment")).Distinct()) {

    @seg

    }`
    – juharr Jul 17 '17 at 13:02
  • 1
    @ElliottJames `If I understood the answer I wouldn't have asked the question` We cannot make that call if you don't specify that you've already tried that option. This is why it's important to show your work, rather than merely ask for a solution. – Flater Jul 17 '17 at 13:03
  • @mjwills - I got the result I needed! – Elliott James Jul 17 '17 at 13:04

1 Answers1

2

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>
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
  • Thanks Camilo for answering the question. @mjwills - Cheers for marking question as a duplicate. Although it's a duplicate, apparently the two answers are different. And the answer the 'duplicate' didn't solve my problem. Bravo. Thanks again Camilo – Elliott James Jul 17 '17 at 13:03
  • 1
    FYI you don't need the `ToList` here. – juharr Jul 17 '17 at 13:04
  • @juharr yes, I know, I just find it more readable with the ToList. – Camilo Terevinto Jul 17 '17 at 13:05