tags:

views:

62

answers:

2
class Program
{
    static void Main(string[] args)
    {
        MyDatabaseEntities entities = new MyDatabaseEntities();

        var result = from c in entities.Categories
                        join p in entities.Products on c.ID equals p.IDCategory
                        group p by c.Name into g
                        select new
                        {
                            Name = g.Key,
                            Count = g.Count()
                        };

        Console.WriteLine(result.ToString());
        Console.ReadLine();
    }
}

How can I extract the values from ths result set so I can work with them?

+9  A: 
foreach (var item in result)
{
    var name = item.Name;
    var count = item.Count;
    ...
}

This will only work inside the same method where the LINQ query is located, since the compiler will only then know which properties are available in the anonymous object type (new { }) used in your LINQ select.

If you return a LINQ query to a calling method, and you want to access it in the way shown above, you'd have to define an explicit type and use it in your LINQ query:

class NameCountType
{
    public string Name { get; set; }
    public int Count { get; set; }
}

...

return from ... in ...
       ...
       select new NameCountType
              {
                  Name = ...,
                  Count = ...,
              };
stakx
I'll accept this answer when the timer ends. I'm a curious guy though; what data type is result exactly? I feel like I'm depending on magic a little too much.
Serg
_@Sergio:_ The compiler will generate an anonymous type for you with `Name` and `Count` defined. If you want to know exactly, you could use Reflection to inspect the details of the generated type.
stakx
@Sergio IQueryable<anonymous type> in your question. IQueryable<NameCountType> in the last example of this answer.
Erv Walter
A: 

For example:

foreach (var x in result)
{
   Console.WriteLine(x.c.Name);
}
shk