2016-07-24 133 views
0

我有一個航班的列表,我試圖用日期字段對它進行分組,然後選擇它進入每個組的最低價格。在結果我應該得到 每天最便宜的航班。如何按字段對列表進行分組,並通過linq選擇另一個字段的分組min?

enter image description here

(from flights in aFlightList 
            where flights.IsDeparture && flights.OnlyTour == "0" && flights.OnlyPhone == "0" 
            group flights by flights.FlightDateFull 
             into grouping 
             select grouping.OrderBy(a => a.FlightDateFull).First()).ToArray(); 

此代碼按日期分組列表,但無法獲得特價機票。 我試試這樣:

(from flights in aFlightList 
            where flights.IsDeparture && flights.OnlyTour == "0" && flights.OnlyPhone == "0" 
            group flights by flights.FlightDateFull 
             into grouping 
             select grouping.OrderBy(a => a.FlightDateFull).Min(d=>d.PriceView)).ToArray(); 

這樣就會出錯。

如何做到這一點?

回答

1

group by操作的結果是一個分組列表,其中分組由一個密鑰和共享該密鑰的元素列表組成。

讓我們開始您的第一個查詢。按操作分組按日期分組aFlightList,因此不需要按日期進一步排序組元素(它是一個且相同的)。但您可以按價格訂購,因此First將以最低價格返回元素。最後,由於group by生成的組的順序可能不是您想要的,您可以通過密鑰(或其一部分)來訂購分組

與所有他這樣說,修改後的查詢可能是這樣的:

(from flights in aFlightList 
where flights.IsDeparture && flights.OnlyTour == "0" && flights.OnlyPhone == "0" 
group flights by flights.FlightDateFull 
into grouping 
orderby grouping.Key 
select grouping.OrderBy(e => e.PriceView).First()) 
.ToArray(); 
1

您可以創建你想要的結果的新對象,並在執行選擇。例如:

class Flight 
    { 
     public bool IsDeparture; 
     public string OnlyTour; 
     public string OnlyPhone; 
     public DateTime FlightDateFull; 
     public decimal PriceView; 
    } 

    [TestMethod] 
    public void FlightTest() 
    { 
     // Arrange 
     var flightList = new List<Flight> { 
      new Flight { IsDeparture = true, OnlyPhone = "0", OnlyTour = "0", FlightDateFull = new DateTime(2016,8,7), PriceView = 1 }, 
      new Flight { IsDeparture = true, OnlyPhone = "0", OnlyTour = "0", FlightDateFull = new DateTime(2016,8,7), PriceView = 2 }, 
      new Flight { IsDeparture = true, OnlyPhone = "0", OnlyTour = "0", FlightDateFull = new DateTime(2016,8,8), PriceView = 2 }, 
      new Flight { IsDeparture = true, OnlyPhone = "0", OnlyTour = "0", FlightDateFull = new DateTime(2016,8,8), PriceView = 3 } 
     }; 

     // Act 
     var result = (from flights in flightList 
         where flights.IsDeparture && flights.OnlyTour == "0" && flights.OnlyPhone == "0" 
         group flights by flights.FlightDateFull into grouping 
         select new { Date = grouping.Key, MinPrice = grouping.Min(a => a.PriceView) }).OrderBy(a => a.Date).ToList(); 

     // Assert 
     Assert.AreEqual(new DateTime(2016, 8, 7), result[0].Date); 
     Assert.AreEqual(1, result[0].MinPrice); 
     Assert.AreEqual(new DateTime(2016, 8, 8), result[1].Date); 
     Assert.AreEqual(2, result[1].MinPrice); 
    } 
相關問題