Thursday, January 14, 2010

Return collection of anonymous type from method in LINQ

Technorati Tags:
Let’s say you have some method that execute a LINQ query over collection and constructs a collection of (new) anonymous type as result. Here is how you can return it and use it below the scope of the method:
public class Program
{
public static IEnumerable<T> GetExampleCollection<T>(T type)
{
// generate some random collection simulating source data
var random = new Random();
var collection =
Enumerable.Repeat(0, 100).Select(
i => new { ClientId = random.Next(), OrderId = random.Next(), Price = random.NextDouble() });

// run some linq query over it
var queryOverCollection = from item in collection
where item.ClientId % 2 == 0
select new { DoublePrice = item.Price * 2.0 };
IQueryable v = (from item in collection
where item.ClientId % 2 == 0
select new { DoublePrice = item.Price * 2.0 }).AsQueryable();

return queryOverCollection as IEnumerable<T>;
}

static void Main(string[] args)
{
// bring collection of anonymous type items from a method!
var v = GetExampleCollection(new { DoublePrice = new double() });
foreach (var item in v)
{
// ... and use it!
Console.WriteLine(item.DoublePrice);
}
}
}



Note, that anonymous type is resolved on the assemble level, so you can’t reference it in another assembly.

No comments: