0

I have a few statements like these:

if (mediaCode.IndexOf(',') > 0) {
  entries = entries.Where(c => mediaCode.Contains(c.Mediacode));
}
else {
  entries = entries.Where(c => c.Mediacode == mediaCode);
}

then:

if (contentType.IndexOf(',') > 0) {
    entries = entries.Where(c => contentType.Contains(c.Contenttype));
}
else {
    entries = entries.Where(c => c.Contenttype == contentType);
}

I would like to create a function where i just pass the string and the property, something like: MethodName(contentType, c.Contenttype)

How could this be done?

noel
  • 585
  • 1
  • 5
  • 10
  • it is not clear what you're asking. Do you want to pass the Expression inside a Linq query to a method? e.g.: entries.Where(conditionParameter) where conditionParameter is c=> mediaCode.Contains(value) – codingadventures Mar 14 '15 at 17:10

1 Answers1

0

Using Reflection (see How to get a property value based on the name), you could do it like this:

    protected void FilterStrings(ref IEnumerable<StringStruct> entries, string contentType, string fieldName)
    {
        if (contentType.IndexOf(',') > 0)
        {
            entries = entries.Where(c => contentType.Contains(c.GetType().GetProperty(fieldName).GetValue(c, null).ToString()));
        }
        else
        {
            entries = entries.Where(c => c.GetType().GetProperty(fieldName).GetValue(c, null).ToString() == contentType);
        }
    }

You would call the function like this:

FilterStrings(ref entries, mediaCode, "Mediacode");
Community
  • 1
  • 1
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146