Need to process objects passed from C# anonymous type

52 views Asked by At

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

1

There are 1 answers

0
Guru Stron On

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);