使用Lambda表达式获取List列表中的最低价格

时间:2015-01-21 11:19:05

标签: c# lambda entity-framework-5

我在实体框架代码优先模式中使用了以下数据模型。我在LINQ Lambda表达式中是新的

问题:

我想计算ItineraryPackagePrice中具有最低价格值的单一行程

public class Region
{
    public int RegionID { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
    public string Name { get; set; }

    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
    public string Type { get; set; }            

    public int? ParentID { get; set; }      

    public virtual Region Parent { get; set; }

    public virtual ICollection<Itinerary> Itinerarys { get; set; }

}

public class Itinerary
{        
    public int ItineraryID { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
    public string Name { get; set; }

    [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
    public string QuoteReferenceNo { get; set; }       

    public virtual ICollection<Region> Regions { get; set; }

    public virtual ICollection<ItineraryPackagePrice> ItineraryPackagePrices { get; set; } 
}

public class ItineraryPackagePrice
{
    public int ItineraryPackagePriceID { get; set; }

    [DataType(DataType.Currency)]
    [Column(TypeName = "money")]
    public decimal Price { get; set; }         

    public int ItineraryID { get; set; }

    public virtual Itinerary Itinerary { get; set; }
}

Lambda Expression:

var db = new dbContext();
var siblingRegions = db.Regions.Where(s => s.ParentID == Model.Region.RegionID).OrderBy(s => s.Name);

// iterating on each resion
foreach (var subreg in siblingRegions)
{
    var singleItinerary = subreg.Itinerarys.
                                 Single(obj => 
                                   new {
                                     Min=obj.ItineraryPackagePrices.
                                     Min(k=>k.Price)});
    //how can I write a query here to calculate minimum price


}

2 个答案:

答案 0 :(得分:2)

试试这个: -

var siblingRegions = db.Regions.SelectMany(x => x.Itinerarys)
                               .SelectMany(x => x.ItineraryPackagePrices)
                               .OrderBy(x => x.Price).FirstOrDefault();

答案 1 :(得分:0)

        var minimumPrice = decimal.MaxValue;
        Itinerary minimumIteneray = null;
        foreach (var subreg in regions)
        {
            foreach (var itinerary in subreg.Itinerarys)
            {
                var minimum = itinerary.ItineraryPackagePrices.Max(p => p.Price);
                if (minimum < minimumPrice)
                {
                    minimumPrice = minimum;
                    minimumIteneray = itinerary;
                }
            }
        }