Alan2
Alan2

Reputation: 24572

Can I use LINQ to query two Lists to populate a single List

I have the following C# classes:

public class Definition
{
    public string partOfSpeech { get; set; } 
    public List<Def> Def { get; set; }
}

public class Def
{
    public string definition { get; set; }
    public List<string> synonyms { get; set; }
}

public class WebWordForm
{
    public string definition { get; set; }
    public string partOfSpeech { get; set; }
    public List<string> synonyms { get; set; }
    public List<string> typeOf { get; set; }
    public List<string> hasTypes { get; set; }
    public List<string> derivation { get; set; }
    public List<string> examples { get; set; }
}

What I have is the a which is a list of Definition

List<Definition> a 

What I would like to do is to create:

List<WebWordForm> = a. << A LINQ statement if possible

Is it possible to do this with a LINQ statement?

Upvotes: 0

Views: 59

Answers (3)

jdweng
jdweng

Reputation: 34421

try this

            List<Definition> a = new List<Definition>();
            List<WebWordForm> words = a.AsEnumerable().Select(x => x.Def.Select(y => new WebWordForm() {
                partOfSpeech = x.partOfSpeech,
                definition = y.definition,
                synonyms = y.synonyms
            }).ToList()
            ).FirstOrDefault();

Upvotes: 0

Hari Prasad
Hari Prasad

Reputation: 16956

Using SelectMany linq extension you could do this.

var result = a.SelectMany(x=> 
               {
                     x.Def.Select(s=> new WebWordForm()
                           {
                               partOfSpeech = x.partOfSpeech,
                               definition  = s.definition,
                               synonyms = s.synonyms,
                              // other properties
                           }).ToList()
                })
               .ToList() ;

Upvotes: 1

Yacoub Massad
Yacoub Massad

Reputation: 27861

You can use a combination of SelectMany and Select to do something like this:

List<WebWordForm> results =
    a.SelectMany(definition => //each definition will generate many WebWordForms
        definition.Def
        .Select(def => new WebWordForm //each def will generate one WebWordForm
        {
            definition = def.definition,
            partOfSpeech = definition.partOfSpeech,
            synonyms = def.synonyms
        }))
    .ToList();

Upvotes: 1

Related Questions