简体   繁体   中英

Need help writing a LINQ statement

I have a Permits entity/table that has a one to many relationship with PermitDetails table. PermitDetails contains information on the limits for those gases represented in the Permits table. The limits are expressed in specific units (GPerBhpHr, LbPerHr etc...).

许可证许可证详细信息许可成分类型

I have a set of properties that my view is databound to (WPF/MVVM) that represent each PermitConstituentType and its corresponding "limit". For Example:

    // this set of properties is duplicated for each gas type (PermitConstiutentType)
    public double NitrousOxidesPpmAt15PercentOxygen {get; set;}
    public double NitrousOxidesLbMmbtuHHV {get; set;}
    public double NitrousOxidesGbhph {get; set;}
    public double NitrousOxidesC3LbHr {get; set;}
    public double NitrousOxidesTpy {get; set;}

Using EF/LINQ I want to query the PermitDetails table and for each PermitConstituentType return the value corresponding to the PermitDetails unit of measure so that it can be assigned to the right Property.

In some cases it will return a null and in other cases it will return a double value. For example in the case where PermitConstituentTypeId = 2 my query would return 92.2 for PpmAt15PercentOxygen. Again, regardless if it is a null that is returned or a value I want to assign the value to the corresponding property.

This statement I have tried gets me the record matching on the PermitConstituentId I want:

var noxRecord = CurrentPermit.PermitDetails.Where(a => a.PermitConstituentTypeId == 2);

But from there I don't know how begin getting values for each of the limits/metrics I need such as PpmAt15PercentOxygen , LbPerMmBtuHHv etc..

Can someone help me finish this LINQ statement or modify it so that I can pull back a specific limit/metric based on the PermitConstituentTypeID?

First, we select the first element:

var noxRecord = CurrentPermit.PermitDetails
                            .FirstOrDefault(a => a.PermitConstituentTypeId == 2);

Then if it's not null, we can use it like an object

if(noxRecord!=null){
    noxRecord.PpmAt15PercentOxygen;// This should be 92.2
}

You are already getting the entity (well, a collection of the entities) with your existing Where clause. You can loop through that for each record that matches your predicate and access the properties you need on that object:

foreach(var noxRecord in CurrentPermit.PermitDetails.Where(a => a.PermitConstituentTypeId == 2)
{
    var ppmAt15PercentOxygen = noxRecord.PpmAt15PercentOxygen;
}

If you only want a single record, do what Benjamin Gruenbaum suggested in his answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM