Filtering a Collection in C#

81 Views Asked by At

I'm currently using SyndicationFeed to extract an image from a syndication item.

Each item has a collection of links. For each link collection I want to do the following:

  1. check the first instance where link.MediaType contains an image,
  2. if it does, return link.Uri else return an empty string

I wanted to do something like this:

var imageLink = image.Links.First(where( s.mediaType contains "image" && s.mediaType != null))
if (imageLink){
  string imageUrl = imageLink.Uri
}

Currently I have a lot of if statements. I'm wondering if there's a cleaner way to do this.

1

There are 1 best solutions below

4
On

Something like this is what you want:

using System.Linq;

string GetUri(SyndicationFeed image)
{
    return image.Links.Where(link => link != null && link.Contains("image")).FirstOrDefault() ?? "";
}