我可以使用LINQ查询两个列表来填充单个列表

时间:2016-06-05 13:06:35

标签: c# linq

我有以下C#类:

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; }
}

我所拥有的是a,它是定义

的列表
List<Definition> a 

我想做的是创建:

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

是否可以使用LINQ语句执行此操作?

3 个答案:

答案 0 :(得分:1)

您可以使用SelectManySelect的组合来执行以下操作:

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();

答案 1 :(得分:1)

使用SelectMany linq扩展程序,您可以执行此操作。

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

答案 2 :(得分:0)

试试这个

            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();