簡體   English   中英

創建一個 <Key,List<Value> &gt;從linq查詢

[英]Creating a <Key,List<Value>> from a linq query

我有兩種型號-國家:

  public int id { get; set; }

  public string CountryName { get; set; }

和FlagColor:

    public int id { get; set; }

    public string Color { get; set; }

    public virtual Country Country { get; set; }

我正在嘗試從linq查詢創建一個對象,該查詢將輸出一個

<CountryName,<列表<ColorOfFlag >>

目前我有

            var combinedList = from c in countries
            join fc in flagColors on c.id equals fc.Country.id
            select new {c, fc};

這幾乎到了,但是每個flagColor返回一行,因此例如

比利時:紅色

比利時:黑色等等

如何將查詢轉換為輸出:

貝爾吉姆(Belguim):{紅色,黑色,黃色}

提示:在LINQ中,您幾乎不需要使用聯接,大多數情況下它是通過關系隱式的。

var combinedList = from fc in flagColors
                   group fc by fc.Country into g
                   select new
                   {
                       Country = g.Key.CountryName,
                       FlagColors = string.Join(",", g.Select(x => x.Color))
                   };

注意:我將其作為易於閱讀的逗號分隔值。 對於列表,您可以執行以下操作:

var combinedList = from fc in flagColors
                       group fc by fc.Country into g
                       select new
                       {
                           Country = g.Key.CountryName,
                           FlagColors = g.Select(x => x.Color).ToList()
                       };

或者,如果您想獲取字典:

var combinedList = (from fc in flagColors
                   group fc by fc.Country into g
                   select new
                   {
                       Country = g.Key.CountryName,
                       FlagColors = g.Select(x => x.Color).ToList()
                   }).ToDictionary(l => l.Country, l=>l.FlagColors);

更短:

var combinedList = flagColors
                   .GroupBy(fc => fc.Country)
                   .ToDictionary(
                       g => g.Key.CountryName, 
                       g=>g.Select(c => c.Color).ToList()
                    );

使用Queryable.GroupBy (或相應的Enumerable.GrouBy)

首先將所有標記顏色歸為一組,其中所有標記顏色均具有相同的countryName ..然后從每個組中創建一個對象,其中包含國家/地區名稱和該組中所有標記顏色的列表:

var result = flagColors
    .GroupBy(flagColor => flagColor.Country.CountryName)
    .Select(group => new
    {
        CountryName = group.Key,                         // get common CountryName
        FlagColors = group                               // get the color of all elements
            .Select(groupElement => groupElement.Color)  // in the group
            .ToList(),
    })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM