I'm getting some data from my database and using linq to calculate sums and counts and group the data. This is what I have:
var si = _repository.GetAllByDate(date);
var cs = from s in si
group s by s.Name into g
select new { Comm = g.Key, SIList = g.ToList(), Count = g.Count() };
i now need to pass cs to a method in another class so that I can extract Comm, SIList and Count for each item in the group, what type do I pass it as? IEnumerable doesn't work. The actual linq group result type seems to be:
{System.Linq.Enumerable.WhereSelectEnumerableIterator<System.Linq.IGrouping<Model.Domain.MasterData
.MyItem,Model.Domain.SI<>f__AnonymousTyped<Model.Domain.MasterData.MyItem,System.Collections.Generic.List<Model.Domain.SI>,int>>}
Any ideas? I effectively want to pass cs as a variable and iterate through it there.
You'll need to create a type that matches the definition of your anonymous type, if it's going to be used in different scopes.
public class SomeClass {
public Comm Comm { get; set; }
public IList<String> SIList { get; set; }
public Int32 Count { get; set; }
}
var si = _repository.GetAllByDate(date);
var cs = from s in si
group s by s.Name into g
select new SomeClass { Comm = g.Key, SIList = g.ToList(), Count = g.Count() };
EDIT: I supposed we can assume that the list will be of String
so I'm editing for that. If that's the wrong type you'll need to change the IList<T>
definition accordingly.
The reason that you get such a complicated type is because the query uses lazy execution. You are looking at the type of the expression that returns the result, not the type of the result.
The type of the result is IEnumerable<_hidden_internal_class_name_>
, i.e. as you are creating anonymous objects in the query, the result is a stream of objects of a class that the compiler creates internally.
It's pretty useless to pass on that result to another method, as it would need to use reflection to read the properties in the objects. You should create a named class for the objects in the result, so that it's easy to access its properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With