我有一个对象列表,其中列表中的每个对象都包含一个对象列表。我需要从子列表中的每个对象中选择一个字符串,并将其包括在主列表中。基本上将子列表弄平。
目标是在电子表格中输入此数据。
class Phrase
{
public string Parent { get; private set; }
public string Value { get; private set; }
}
class Translation
{
public string Key { get; private set; }
public string Translatable { get; private set; }
public List<Phrase> Phrases { get; private set; }
}
{ Key = "coffee", Translatable = "", Phrase = [{ Parent = "English", Value = "Coffee" }, { Parent = "Swedish", Value = "Kaffe" }] },
{ Key = "candy", Translatable = "", Phrase = [{ Parent = "English", Value = "Candy" }, { Parent = "Swedish", Value = "Godis" }] },
{ Key = "computer", Translatable = "", Phrase = [{ Parent = "English", Value = "Computer" }, { Parent = "Swedish", Value = "Dator" }] }
正如我所说,目标是将这些数据插入电子表格中,因此根据上面的列表,电子表格理论上应如下所示:
Key | Translatable | English | Swedish
---------------------------------------------
coffee | | Coffee | Kaffe
candy | | Candy | Godis
computer | | Computer | Dator
我只关心短语对象中的Value
。
您可以像这样从列表中选择Key
和Translatable
var query = from t in parser.translations
from p in t.Phrases
select new { t.Key, t.Translatable };
会产生
{ Key = "coffee", Translatable = ""},
{ Key = "candy", Translatable = ""},
{ Key = "computer", Translatable = ""}
但是我该如何将短语列表中的所有值包括到每个对象中?目标将是这样的:
{ Key = "coffee", Translatable = "", Value1 = "Coffee", Value2 = "Kaffe"},
{ Key = "candy", Translatable = "", Value1 = "Candy", Value2 = "Godis"},
{ Key = "computer", Translatable = "", Value1 = "Computer", Value2 = "Dator"}
任何帮助表示赞赏。
答案 0 :(得分:0)
如果您总是在短语中有两个键(英语,瑞典语)并且只需要值。 你可以试试看。
为结果添加新的类
class tr
{
public string Key { get; set; }
public string trn { get; set; }
public string English { get; set; }
public string Swedish { get; set; }
}
并使用此查询
var query = from t in translations
select new tr()
{
Key = t.Key,
trn = t.Translatable,
English = t.Phrases.Single(p => p.Parent == "English").Value,
Swedish = t.Phrases.Single(p => p.Parent == "Swedish").Value
};