MVC复杂数据查询

时间:2013-02-13 01:02:26

标签: asp.net-mvc-3 linq lambda entity-framework-5

我的查询如下: `表

  1. 伦敦公寓
  2. 伦敦公寓
  3. 伦敦之家
  4. 巴黎公寓
  5. 巴黎公寓
  6. 巴黎之家
  7. Paris House`
  8. 我希望将它转换为linq中的下方对象。有人请帮助我。

     public class BrowseModel
    {
        public string TownName { get; set; }
    
        public int FlatCount { get; set; }
    
        public int HouseCount { get; set; }
    
    }
    

    结果必须如下:

    1. 伦敦2Flat 1 house
    2. 巴黎2Flat 2房屋

1 个答案:

答案 0 :(得分:0)

如果我不明白你的问题,你可以像这样试试

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        //Ignore above code
        List<Table> list = new List<Table>();
        //Suppose this what you db returns
        list.Add(new Table() { TownName = "London", HouseType = HouseType.Flat });
        list.Add(new Table() { TownName = "London", HouseType = HouseType.Flat });
        list.Add(new Table() { TownName = "London", HouseType = HouseType.House });
        list.Add(new Table() { TownName = "Paris", HouseType = HouseType.Flat });
        list.Add(new Table() { TownName = "Paris", HouseType = HouseType.Flat });
        list.Add(new Table() { TownName = "Paris", HouseType = HouseType.House });
        list.Add(new Table() { TownName = "Paris", HouseType = HouseType.House });

        var result = list.GroupBy(o => o.TownName).Select(s => new BrowseModel() { TownName = s.First().TownName, FlatCount = s.Where(f => f.HouseType == HouseType.Flat).Count(), HouseCount = s.Where(h => h.HouseType == HouseType.House).Count() }).ToList();
    } 
}

public class BrowseModel
{
    public string TownName { get; set; }

    public int FlatCount { get; set; }

    public int HouseCount { get; set; }

}

public class Table
{
    public string TownName { get; set; }
    public HouseType HouseType { get; set; }
}

public enum HouseType
{ 
    House=0,
    Flat=1
}

我希望这会给你一个想法。