Andrew
Andrew

Reputation: 2325

LinqtoSQL SelectMany type arguments cannot be inferred from usage

I'm trying to create a LINQ statement to flatten some data from my database. An example row could look as follows:

LegislationCode LanguageCode
=============== ============
CHN|JPN|KOR ENG

What I need to do is to flatten this dataset so I am left with the following:

CHN ENG
JPN ENG
KOR ENG

This is just an example - there are many more in the database that need this to be done as well.

I am using LINQtoSQL to connect to my database and the following query (which doesn't compile) to try and achieve this:

var result = pContext.LanguageLegislations.AsEnumerable()
                     .Select(ll => new
                     {
                         LangCode = ll.LanguageCode,
                         LegCode = ll.LegislationCode.Split('|').ToList()
                     })
                     .SelectMany(ll2 => ll2, (l) => new { l.LegCode, l.LangCode }) // doesn't compile
                     .ToList();

The error message I get is as follows:

Error 1 The type arguments for method 'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I can replace the non compiling line with the following and it returns a flattened list of LegislationCode, but I need to be able to associate this legislation code with a language.

.SelectMany(ll2 => ll2.LegCode)

I've done a bit of research and most of the examples I can find seem to be using data objects, which have mappings between the child-parent objects, but this is not the case here.

Any help appreciated.

Upvotes: 1

Views: 1832

Answers (1)

Douglas
Douglas

Reputation: 54927

I would nest the Select projection that constructs your anonymous type within the SelectMany projection that flattens the nested lists.

var result = 
    pContext.LanguageLegislations.AsEnumerable()
            .SelectMany(ll => ll.LegislationCode.Split('|').Select(legCode => new
            {
                LangCode = ll.LanguageCode,
                LegCode = legCode
            }))
            .ToList();

Upvotes: 2

Related Questions