Linq Group by With投射到列表中

时间:2018-10-10 15:44:27

标签: c# linq

我正在尝试按对象分组并将其投影到列表中,这样列表属性的每个元素都会在此新列表中生成一个投影对象。

源对象是这样的:

来源就像:

[
  {
    Language: "EN",                                         
    TargetLanguages: [
       "FR",
       "IT",
       "DE"                                        
     ]
  },
  {
    Language: "FR",                                         
    TargetLanguages: [
          "PT",
          "IT",
          "DE"                                        
       ]
  },
  {
     Language: "EN",                                         
     TargetLanguages: [
          "FI",
          "PT"                               
        ]
    }
]

我需要按语言和目标语言分组 到目前为止,我的情况是这样:

var requestsGroupedBySl = nonEuTranslationRequests
                .GroupBy(nonEu => new {
                    nonEu.TranslationSource.Language
                })
                .Select(nonEu => new
                {
                    nonEu.Key.Language,
                    targetLanguages =nonEu.SelectMany(request => request.TargetLanguages)
                })
                .ToList();

哪个给我这个:

Language: "EN",
TargetLanguage: [
    "FR",
    "IT",
    "DE"                                        
]

我真正想要的是,每个唯一的language-targetLanguage对都有一个对象。

[
    {
        Language: "EN",                                         
        TargetLanguage: "FR"
    },
        {
        Language: "EN",                                         
        TargetLanguage: "IT"
    },

        {
        Language: "EN",                                         
        TargetLanguage: "DE"
    }

]

我该如何实现?

2 个答案:

答案 0 :(得分:2)

您应该在组中更改.Select的逻辑:

var result = nonEuTranslationRequests
            .GroupBy(i => i.TranslationSource.Language)
            .Select(g => g.SelectMany(r => r.TargetLanguages).Select(i => new {
                g.Key.Language,
                TargetLanguage = i
            })
            .ToList();

此外,当您按单个属性分组时,无需创建匿名对象进行分组。

答案 1 :(得分:0)

您也可以在@GiladGreen解决方案中使用值元组代替匿名对象。试试这个:

new Date("11/10/2015 10:00:00 GMT")

请注意,您应该使用С#7和.NET Framework> = 4.7

查看更多:https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple?view=netframework-4.7.2