If you are using LINQ and create a new anonymous type, this object can be passed to a function by using a parameter of type object. But if you, want to use the properties a more cleaner approach would be using the dynamic keyword in C#:

using System;
using System.Linq;
using System.Dynamic;
using System.Collections.Generic;
using Microsoft.CSharp;
[TestMethod]
public void Test()
{
    PassingObjectsOfAnAnonymousTypeToAFunction();   
}
public void PassingObjectsOfAnAnonymousTypeToAFunction()
{
    // Create a list of names.
    List<string> names = new List<string>();
    names.Add("Name_1");
    names.Add("Name_2");
    names.Add("Name_20");
    names.Add("Name_3");

    // Filter names.
    var query = from n in names
                where n.Contains("2")
                select new { Name = n, MyExtraProperty = "Added some extra property" };
    var filteredItems = query.ToList();

    // Write filtered names to console.
    foreach (var fi in filteredItems)
    {
        FunctionWithAnonymouseParameters(fi);
    }
}
public void FunctionWithAnonymouseParameters(dynamic name)
{
    Console.WriteLine(string.Format("Name=[{0}] MyExtraProperty=[{1}]", name.Name, name.MyExtraProperty));
}

Result

 

Name=[Name_2] MyExtraProperty=[Added some extra property]

Name=[Name_20] MyExtraProperty=[Added some extra property]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.