0

Lets say I have an method which returns an object. I return a new object which contains two properties Sum and Count. When I call this method, How can I retrieve these properties?

public static object SomeMethod(){
   using (var context = new MappedTableEntities()){
      return from x in context.SomeMappedTable
                   group x by 1 into g
                   select new
                   {
                       Count = g.Count(),
                       Sum = g.Sum(col => col.someSummableColumn)
                   };
       }
}

when I call this function:

var obj = SomeClass.someMethod();

I do not see the properties exposed and I get a compiler error when I try to retrieve them. How can I expose these members?

/*ERROR */
var count = obj.Count;
var sum = obj.Sum;
Cœur
  • 37,241
  • 25
  • 195
  • 267
Shayan Zafar
  • 113
  • 1
  • 13
  • Just for the record, this is why anonymous types are such a bad idea in most cases. Also, the linked duplicate was the first result of a search for "retrieve properties of anonymous type C#". Perhaps you didn't know that you were creating an anonymous type, but it makes me feel sad when I find a duplicate that quickly :( – BradleyDotNET Oct 02 '14 at 01:28
  • Yeah I didn't know this was a subcategory. Sorry about that. – Shayan Zafar Oct 02 '14 at 01:33
  • No problem, now you know, and learned two things! – BradleyDotNET Oct 02 '14 at 01:36
  • I have a problem, The solution for the question that this is linked to, does not work for an object return from select new {prop, prop2}. This is form a LINQ to Entity Framework query which was using the Count and Sum Aggregator functions – Shayan Zafar Oct 02 '14 at 02:00
  • @BradleyDotNET can you re-open this? – Shayan Zafar Oct 02 '14 at 02:17
  • Did you try the dynamic or reflection solutions? Its still effectively the same problem. I am considering re-opening it, but would like to know if either of those worked for you. You could always just use a strong type of course, but that doesn't really answer your question (though it may be easier!). – BradleyDotNET Oct 02 '14 at 04:23
  • Yes ive tried them both to no avail. I had to separate the query out into two queries. But this seems inefficient. I would assume it can be done in one query. – Shayan Zafar Oct 02 '14 at 06:24
  • 1
    Alright. I re-opened it. I think the answer is really to use a strong type. – BradleyDotNET Oct 02 '14 at 16:42

0 Answers0