0

I have an anonymous type that is structured as follows:

{Contact = {BO.AgtContact}, Agency = {BO.Agent}}  

AgtContact and Agent are classes

I am currently looping over the anonymous type in my main block of code to process its contents.

I would like to extract this out to a method something like

public someReturnType MyMethod(IEnumerable<dynamic> list)
{
   Loop over list
      var contact = list.AgtContact
      contact.field = set field value
   End loop

   return someReturnType (same as IEnumerable<dynamic> that was passed in)
}

I hope this makes sense. Any help greatly appreciated

David
  • 208,112
  • 36
  • 198
  • 279
HABosch
  • 49
  • 3

1 Answers1

1

I would highly recommend to just create a type (it is quite convenient in latest language versions with records) and use it instead of the anonymous one.

Alternatively you can try using generics. Something along these lines:

public ICollection<T> MyMethod<T>(IEnumerable<T> list, Func<T, AgtContact> getter)
{
    var enumerated = list as ICollection<T> ?? list.ToArray();
    foreach (var t in enumerated)
    {
        var agtContact = getter(t); //since AgtContact is a class
        agtContact.PropOfField = ...;
    }

    return enumerated;
}

And usage:

var colletionOfAnonTypes = ...
MyMethod(colletionOfAnonTypes, arg => arg.Contact);
Guru Stron
  • 102,774
  • 10
  • 95
  • 132