Linq投射到一堂课

时间:2016-08-08 17:44:09

标签: c# asp.net-mvc

public class MarketViewModel
{
    public MarketViewModel()
    {
    }

    public string Item { get; set; }
    public List<SubItem> StationName { get; set; }

}

public class SubItem
{
    public string Item { get; set; }
}

var active = from actives in activeStations
    group actives.StationName by new { actives.Market,actives.StationGroupInt } into g
    select new MarketViewModel { Item = g.Key.Market, StationName = g.tolist() };

在上面的LINQ代码中,我的问题是我如何投影到MarketviewModel,因为你看到stationname是一个subItem列表。

StationName = g.tolist()

(如何重新编写这篇文章?)以便创建子项目对象列表

修改

activestations实体包含

  • 工作站名称(字符串),
  • stationgroupInt(int),
  • 市场(字符串)
market stationName StationgroupInt
----------------------------------

A       B              1
A       C              1
A       D              1 

1 个答案:

答案 0 :(得分:0)

您可以在群组Select上使用g来创建子项目。

var active = from actives in activeStations
             group actives.StationName by new { actives.Market,actives.StationGroupInt } into g
             select new MarketViewModel { 
                 Item = g.Key.Market, 
                 StationName = g.Select(stationName => new SubItem { 
                     Item = stationName 
                 }).Tolist() 
             };