Iterate through LINQ AnonymousType Object

How to use the result of this LINQ in another method and get the CountryID and count properties?

 public IQueryable GetRequestsByRegion(string RequestType) { try { var q = from re in context.RequestExtensions from r in context.Requests where re.ExtensionID == r.ExtraInfoID && r.OriginalRequestID == null && r.RequestType == RequestType group re by new { CountryID = re.CountryID } into grouped select new { CountryID = (int)grouped.Key.CountryID, count = (int)grouped.Count(t => t.CountryID != null) } ; return q; } catch (Exception ex) { } return null; } public void GetAllInformationRequestsByRegion() { IQueryable dict = GetRequestsByRegion("tab8elem1"); /* How to iterate and get the properties here? */ } 

Inverse types and variable types do not have to be specified ... It was my attempt. I also use WCF, so I cannot return object types.

+4
source share
4 answers

Just as if it were some other object:

 foreach(var obj in q) { var id = obj.CountryID; var count = obj.count; } 
+6
source

Additional

Perhaps you want to use this outside the method? Then use something like this:

 public void ForEach<T>(IEnumerable<T> l, Action<T> a) { foreach (var e in l) a(e); } 

Using:

 ForEach(from x in bar select new { Foo = x, Frequency = 4444, Pitch = 100 }, x => { //do stuff here Console.WriteLine(x.Foo); Console.Beep(x.Pitch,x.Frequency); }); 
+2
source

You can handle the result just like a regular C # object. Intellisense helps you with anonymous typing.

 foreach (var anonymousObject in q) { // anonymousObject.CountryID; // anonymousObject.count; } 
+1
source

Anonymous types are local to the method in which they are declared. You cannot return them directly. If you want them to appear outside the declaration method, you need to create a project that you can name (either your own custom class, or some other existing infrastructure class, such as KeyValuePair).

0
source

All Articles