Getting Values ​​from Linq GroupBy

I have a datatable that contains a load of dates. I wanted to group them by date and give each line an account.

I managed to do this through dong:

IEnumerable query = from row in stats.AsEnumerable() group row by row.Field<string>("date") into grp select new { Date = grp.Key, Count = grp.Count(t => t["date"] != null) }; 

(where "statistics" is data)

From debugging, I can see that this returns values ​​grouped as needed, but now I need to encode them and get each date and count.

My problem is that I do not know how to get the values!

I have a foreach loop

 foreach (var rw in query) { string date = rw.Date; // <---- this is my problem? } 

I do not know what type of Ienumerable should be able to refer to the values ​​in it!

So my question is, how can I get each date and count for each row by doing similar to the above?

Hope this makes sense!

+4
source share
3 answers

This link on my blog should help you http://www.matlus.com/linq-group-by-finding-duplicates/

Essentially, your type is an anonymous type, so you cannot refer to it as a type, but you can access the properties you are trying to make.

I think I see your problem. If you are trying to return it from a method, you must determine the type and repeat it as shown below:

 public IEnumerable<MyType> GetQuery() { var query = from row in stats.AsEnumerable() group row by row.Field<string>("date") into grp select new { Date = grp.Key, Count = grp.Count(t => t["date"] != null) }; foreach (var rw in query) { yield return new MyType(rw.Date, rw.Count); } } 

declare the variable "query" using "var" as shown above.

+1
source

I think you do not have access to the properties of the anonymous class, because you are using IEnumerable query = ... Instead, try var query = ...

0
source

Following your comment “I am returning a request from a function”, which I mean that you want to execute the request in the method, return the data to the caller, and then iterate over the data in the caller, I suggest you return Dictionary<DateTime, int> , for example:

 static Dictionary<DateTime, int> GetSummarisedData() { var results = ( from row in stats.AsEnumerable() group row by row.Field<string>("date") into grp select new { Date = grp.Key, Count = grp.Count(t => t["date"] != null) }) .ToDictionary(val => val.Date, val => val.Count); return results; } 

then in the caller you can just

 foreach (var kvp in GetSummarisedData()) { // Now kvp.Key is the date // and kvp.Value is the count } 
0
source

Source: https://habr.com/ru/post/1339340/


All Articles