Reputation: 7667
I have a collection of Schemas
, where each Schema has Name
, Id
and several other properties. I need to project just the Name
and Id
of every Schema
and thus I am creating an anonymous type in the LINQ query as follows:
from s in db.Schemas
select new { Id = s.SchemaId, Name = s.Name}
I need to convert the above anonymous type projected via the Select
query operator to a Dictionary<int,string>
and for that I need to add a further extension method overload to the above query as follows:
(from s in db.Schemas
select new { Id = s.SchemaId, Name = s.Name})
.ToDictionary<TSource,int,string>()
Now, how can I access the anonymous type in the ToDictionary()
overload?
What should I replace TSource
type parameter with?
I have other methods to do this, but I am wondering if it can be done in this way by accessing the anonymous type. Any other nice method to do this are also welcome.
Upvotes: 0
Views: 88
Reputation: 50154
You can elide the type arguments completely.
(from s in db.Schemas
select new { Id = s.SchemaId, Name = s.Name})
.ToDictionary(p => p.Id, p => p.Name);
The compiler can infer them for you.
In fact, you may be able to do this in a single step:
db.Schemas.ToDictionary(s => s.SchemaId, s => s.Name);
or at least by sticking with one type of LINQ syntax:
db.Schemas
.Select(s => new { Id = s.SchemaId, Name = s.Name })
.ToDictionary(p => p.Id, p => p.Name);
Upvotes: 4