user1005310 user1005310 - 3 months ago 23
C# Question

Linq projecting to a class

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


In the above LINQ code, my question is how do I project to
MarketviewModel
, as you see stationname is a list of subItem.

StationName = g.tolist()

( how do I re-write this piece ?) so that it creates a list of subitem objects

EDIT

activestations entity contains


  • stationName(string),

  • stationgroupInt (int),

  • market (string)






market stationName StationgroupInt
----------------------------------

A B 1
A C 1
A D 1

Answer

You can use Select on group g to create the sub item.

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