OrderBy在LINQ中使用WHERE

时间:2017-04-19 10:39:41

标签: c# linq

我有offerList

类型的列表Offer
public class Offer
{
    public List<Feature> FeatureList { get; set; }

}

public class Feature
{
    public string FeatureName { get; set; }
    public string Value { get; set; }
}

现在,我正在尝试获取Offer,其FeatureName为“Int”,其最大值为属性Value。我试过以下LINQ 但它给出了错误

  

Offer'不包含'Value'的定义,也没有扩展名   方法'Value'接受'Offer'类型的第一个参数可以是   发现(您是否缺少using指令或程序集引用?)

List<Offer> offerList = resp;
Offer filteredOffer = offerList
    .Where(x => x.VerticalType == VerticalType.HighSpeedInternet)
    .Where(x => x.FeatureList.Any(y => y.FeatureName == "INT"))
    .OrderByDescending(y => y.Value)
    .FirstOrDefault();

我错过了什么?

3 个答案:

答案 0 :(得分:3)

假设内部FeatureList包含具有属性Value的对象,并且您希望只有一个对象具有所需的FeatureName,并且您希望按其排序Value {{ 1}}:

List<Offer> offerList = resp
   .Where(x => x.VerticalType == VerticalType.HighSpeedInternet)
   .Select(x => new 
   {
       Offer = x,   
       SpeedFeature = x.FeatureList
           .Where(y => y.FeatureName == "INT")
           .OrderByDescending(y => y.Value)
           .FirstOrDefault()
   })
   .Where(x => x.SpeedFeature != null)
   .OrderByDescending(x => x.SpeedFeature.Value)
   .Select(x => x.Offer)
   .ToList();

如果您希望具有最高值的单个OfferToList替换为FirstOrDefault

答案 1 :(得分:2)

List<Offer> offerList = resp;
Offer filteredOffer = offerList
    .Where(x => x.VerticalType == VerticalType.HighSpeedInternet)
    .Where(x => x.FeatureList.Any(y => y.FeatureName == "INT"))
    .OrderByDescending(y => y.FeatureList.Where(x => x.FeatureName == "INT").Max(u => u.Value))
    .FirstOrDefault();

答案 2 :(得分:1)

我怀疑这是你之后的事情:

List<Offer> offerList = resp;
var filteredQuery = from offer in offerList
                    where offer.VerticalType == VerticalType.HighSpeedInternet
                    from feature in offer.FeatureList
                    where feature.FeatureName == "INT"
                    orderby feature.Value desc
                    select new { offer, feature };

Offer filteredOffer = filteredQuery.FirstOrDefault()?.offer;

它将搜索单个最高价值的INT功能,并返回其所属的功能和优惠。