Search code examples
c#.netattributescustom-attributessyncfusion

How to obtain a specific custom attribute when OfType is not available in C#?


In my application I'm trying to obtain a specific attribute using a foreach loop:

Datasource of foreach:

enter image description here

Now I'd like to check for each property if it has the "EditTemplate" CustomAttribute, and if the property has it, put this attribute in a variable like this:

enter image description here

Foreach:

@foreach (var property in EditObject.GetType().GetProperties())
{
      var attributes = property.GetCustomAttributes(true);
      var DoSomeAttribute = attributes;

      //THIS IS THE PART THAT DOES NOT WORK BECAUSE .OfType is not recognized
      //var attribute = property.GetCustomAttributes(true).OfType<EditTemplateAttribute>().FirstOrDefault();
}

The line of code "var attributes = property.GetCustomAttributes(true)" giving me an object with x amount of items(Attributes within):

enter image description here

Now this is where I want to do a check if the attribute is of Type "EditTemplateAttribute", if this is the case I want to put it in a variable like this:

enter image description here

In another piece of code(and another foreach) I achieved this by:

var attribute = property.GetCustomAttributes(true).OfType<EditTemplateAttribute>().FirstOrDefault();

However the .OfType is not available here.

Does anyone know how to achieve this?

Thanks in advance!


Solution

  • I don't know why .OfType should be unavailable. Try adding using System.Linq. This is the namespace where OfType extension method is defined.

    I've noticed that your foreach is prefixed with '@'. Are you using MVC Razor view? In that case you can add using like: @using System.Linq

    In any case you can replace .OfType<EditTemplateAttribute>() with:

    .Where(x => x is EditTemplateAttribute).Select(x => (EditTemplateAttribute)x)

    Or you can use (may return attribute instance or null):

    var someAttribute = (EditTemplateAttribute)attributes.FirstOrDefault(x => x is EditTemplateAttribute);
    

    Or, you can write your own OfType extension method (and use it like you wanted at first):

    public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source)
    {
      foreach (object obj in source)
      {
        if (obj is TResult)
          yield return (TResult) obj;
      }
    }