KayBee718
KayBee718

Reputation: 41

LINQ ToDictionary From Enumerable of Anonymous Object

The ToDictionary() method call in this LINQ statement needs arguments. As it currently stands, the ToDictionary portion is a red squiggly, for lack of a better technical term. Error: No overload takes 0 arguments. Yeah, I know that.

I cannot add lambdas to the ToDictionary method call because Intellisense is overriding my lambda with its suggestion. In other words, if I type in "x ", it replaces it with XmlReader. Argh.

I've tried it with and without AsEnumerable. I borrowed most of this code from a StackOverflow post, but I added the dictionary portion.

Am I missing parentheses somewhere or something? Halllllp!

var props = (from p in _type.GetProperties()
             let attr = p.GetCustomAttribute<ExcelExportAttribute>()
             where attr != null && attr.ReportId.ToString() == reportID
             select new {Prop = p, Att = attr })
             .AsEnumerable()
             .ToDictionary<PropertyInfo, ExcelExportAttribute>();

Error in VS

Severity Code Description Project File Line Suppression State Error CS1929 'IEnumerable<>' does not contain a definition for 'ToDictionary' and the best extension method overload 'Enumerable.ToDictionary(IEnumerable, Func, IEqualityComparer)' requires a receiver of type 'IEnumerable' WFG.UtilityLib.Excel C:\Users\kbessel\source\repos\WFG.UtilityLib.Excel\WFG.UtilityLib.Excel\ExcelExport.cs 142 Active

Upvotes: 1

Views: 2335

Answers (2)

Peter B
Peter B

Reputation: 24187

You need to completely leave out the generic types, like this:

.ToDictionary(x => x.Prop, x => x.Att);

The reason is that the extension method would need not two but THREE generic types: one for the "this" parameter, and two more for the "regular" parameters - or none, because the compiler can derive the types from the parameters.

You can specify all 3 types explicitly, but that would hardly serve any purpose because they can be derived automatically.

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

I cannot add lambdas to the ToDictionary method call because Intellisense is overriding my lambda with its suggestion. In other words, if I type in "x ", it replaces it with XmlReader.

This is a straightforward problem to overcome: type x, then press Esc to close down Intellisense drop-down. Continue typing the expression as needed:

var props = _type.GetProperties()
    .SelectMany(p => new {Prop = p, Attr = p.GetCustomAttribute<ExcelExportAttribute>()})
    .Where(p => p?.ReportId?.ToString() == reportId)
    .ToDictionary(p => p.Prop, p => p.Attr);

Upvotes: 3

Related Questions