2
var emp = (from a in AdventureWorks.PersonPhones
                               join b in AdventureWorks.People
                               on a.BusinessEntityID equals b.BusinessEntityID
                               join c in AdventureWorks.PhoneNumberTypes
                               on a.PhoneNumberTypeID equals c.PhoneNumberTypeID
                               select new { a, b, c }).OrderBy(n => n.c.Name);

I have this linq query which selects values in a anonymous type class. I just want to pass this query to somemethod() and call toList() on this query stored in "emp" in that method. Thanks!

leppie
  • 115,091
  • 17
  • 196
  • 297
Faisal Amjad
  • 33
  • 1
  • 6
  • http://stackoverflow.com/questions/55101/how-can-i-pass-an-anonymous-type-to-a-method http://stackoverflow.com/questions/6624811/how-to-pass-anonymous-types-as-parameters – dugas May 29 '13 at 21:00
  • You can represent this type as an `IEnumerable`. Though I'm not sure if you can that as a parameter type to methods? Better yet, why not create a class type for `{ a, b, c }`, and then pass it as an `IEnumerable`? – Porkbutts May 29 '13 at 21:54

3 Answers3

3

It's possible to do this in a way that doesn't care if it's a anonymous type or not - and if you pass a method for picking out the relevant property you can even do some work on it.

private static void Process<T>(IEnumerable<T> data, Func<T, string> selector) {
    foreach (var item in data) {
        Console.WriteLine(selector(item));
    }
}

var items = from i in db.table
            select new { property = i.originalProperty, ignored = i.ignored };
Process(items, (item => item.property));

An alternative to this would be to just select the property you want into a new list

var items = from i in db.table
            select new { prop1 = i.prop1, prop2 = i.prop2 };
// ... cut ... do something that requires everything in items ...
IEnumerable<string> justFirstProperties = items.Select(i => i.prop1);
Process(justFirstProperties);
Rob Church
  • 6,783
  • 3
  • 41
  • 46
  • FYI: http://stackoverflow.com/questions/6624811/how-to-pass-anonymous-types-as-parameters – Shog9 Nov 22 '13 at 05:16
1

You can't pass anonymous types around in a strongly typed way (only as object). You would have to create a type to represent the anonymous type structure, use reflection on the object type, or do the ToList() etc. work in this method.

Haney
  • 32,775
  • 8
  • 59
  • 68
0

You could pass it as IQueryable<dynamic>

public void SomeQueryMethod(IQueryable<dynamic> query)
{
       var result = query.First();

       var a = result.a; //dynamic resolution
} 
.... 
SomeQueryMethod(emp); //this should work

But in the method all property access on the result objects will be "dynamic", without compile time checks.

Jurica Smircic
  • 6,117
  • 2
  • 22
  • 27