[英]GroupBy a list of tuple c#
我有一組需要轉換為其他格式的結果。 結果來自Dictionary<string, List<Tuple<string, string>>>
資源。 關鍵是語言文化LCID,元組是中性文本和本地化文本。
例如,給出的結果是:
1. 3084, [0]: Female : Femme, [1] Man : Homme, [2] Other : Autre
2. 1033, [0]: Female : Women, [1] Man : Man, [2] Other : Other
因此,現在我需要按中性文本按組對這些數據進行轉換。 最后一組值需要適合此類:
public class StructuredLocalized
{
public string NeutralText { get; set; }
public Dictionary<string, string> LocalizedTexts { get; set; }
}
最終結果應該是這樣的:
1. Female, [0]: 3084 : Femme, [1]: 1033: Women
2. Man, [0]: 3084 : Homme, [1] : 1033 : Man
3. Other, [0]: 3084 : Autre, [1]: 1033 : Autre
我無法編寫group by子句來實現該格式。 有人可以幫忙嗎?
嘗試
var tmp = (from r in x select (from v in r.Value select new { r.Key, v.Item1, v.Item2}))
.SelectMany(a=>a).ToLookup(a=>a.Item1 , a => new { a.Key, a.Item2});
var results = (from r in tmp select new
StructuredLocalized{
NeutralText = r.Key ,
LocalizedTexts = r.ToDictionary(a=>a.Key, a=>a.Item2)
} ) ;
int line = 1;
foreach(var r in results)
{
Console.Write ("{0}. {1}," , line++, r.NeutralText);
int j = 0;
foreach(var k in r.LocalizedTexts)
{
Console.Write(" [{0}]: {1} {2}, " , j++, k.Key, k.Value);
}
Console.WriteLine();
}
我相信這就是您要尋找的。 訣竅是在組合之前將字典拼合成包含3個值的匿名對象。 但是,如果可以的話,我建議創建特定於您域的類型。
var idToNames = new Dictionary<string, List<Tuple<string, string>>>
{
{
"3084",
new List<Tuple<string, string>>
{
Tuple.Create("Female", "Femme"),
Tuple.Create("Male", "Homme"),
Tuple.Create("Other", "Autre"),
}
},
{
"1033",
new List<Tuple<string, string>>
{
Tuple.Create("Female", "Woman"),
Tuple.Create("Male", "Man"),
Tuple.Create("Other", "Other"),
}
}
};
var nameToSpecific =
idToNames.SelectMany(
kvp => kvp.Value.Select(
t => new
{
LCID = kvp.Key,
GenericName = t.Item1,
SpecificName = t.Item2
}))
.GroupBy(x => x.GenericName)
.ToDictionary(
g => g.Key,
g => g.Select(
x => Tuple.Create(x.LCID, x.SpecificName)).ToList());
foreach (var kvp in nameToSpecific)
{
Console.WriteLine(kvp.Key);
foreach(var tup in kvp.Value)
Console.WriteLine(" " + tup);
}
結果
Female
(3084, Femme)
(1033, Woman)
Male
(3084, Homme)
(1033, Man)
Other
(3084, Autre)
(1033, Other)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.