0

我有一个查询如下:`表

  1. 伦敦公寓
  2. 伦敦公寓
  3. 伦敦之家
  4. 巴黎公寓
  5. 巴黎公寓
  6. 巴黎之家
  7. 巴黎之家`

我希望将其转换为 linq 中的以下对象。任何人请帮助我。

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

    public int FlatCount { get; set; }

    public int HouseCount { get; set; }

}

结果需要像:

  1. 伦敦 2Flat 1 house
  2. 巴黎 2平 2 房子
4

1 回答 1

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
}

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

于 2013-02-13T13:31:56.967 回答