c# - 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}
解决方案
提示:在 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()
);
推荐阅读
- c++ - 在 C++ 中最小化变量的范围
- reactjs - 背景图片在手机上没有响应
- delphi - 为什么 FMX TabControl 中的选项卡选择箭头在运行时消失?
- python - 我正在尝试在弹出窗口中使用 python 和 kivy 显示图像,但我收到此错误,我不知道如何修复它
- c++ - 在模板类中构造一个类
- typescript - Firebase 函数无法识别 index.ts 之外的快速应用程序路由
- python - 如何将表格从网页导出到 csv?
- python - 创建一组字典时出错
- python - HTTP 错误 508:检测到循环 python urllib.request
- c++ - 字符串流的行为与常规流 c++ 不同