2013-02-13 47 views
0

我有如下的查询: `表MVC复杂的数据查询

  1. 伦敦的公寓
  2. 伦敦的公寓
  3. 伦敦之家
  4. 巴黎的公寓
  5. 巴黎的公寓
  6. 巴黎之家
  7. Paris House'

我期待在linq中把它变成下面的对象。任何人都请帮助我。

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

    public int FlatCount { get; set; } 

    public int HouseCount { get; set; } 

} 

结果需要像:

  1. 伦敦2Flat 1个
  2. 巴黎2Flat 2房
+0

是您转换为BrowseModel的字符串列表类型 – ethicallogics 2013-02-13 02:21:28

+0

它是一个对象。想象一下房子的对象。平和房子是房子类型。 – Tun 2013-02-13 10:08:24

回答

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 
} 

我希望这会给你想法。

+0

谢谢你。这非常有帮助。 – Tun 2013-02-13 14:08:29