首页 > 解决方案 > Creating a > from a linq query

问题描述

I've got two models - Country:

  public int id { get; set; }

  public string CountryName { get; set; }

and FlagColor:

    public int id { get; set; }

    public string Color { get; set; }

    public virtual Country Country { get; set; }

I am trying to create an object from a linq query that would output an object of

< CountryName,< List < ColorOfFlag>>

currently at the moment I have

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

This is almost there but it is returning a row per flagColor so e.g

Belgium: Red

Belgium: Black and so forth

how do I convert my query to out put:

Belguim: { Red, Black, Yellow}

标签: c#linq

解决方案


提示:在 LINQ 中,您几乎不需要使用 join,大多数情况下它是通过关系隐含的。

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()
                    );

推荐阅读