我有以下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语句执行此操作?
答案 0 :(得分:1)
您可以使用SelectMany和Select的组合来执行以下操作:
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();