在WCF数据服务中为LINQ查询构建where子句

时间:2011-05-09 15:59:07

标签: c# linq where

我有一个传递一个或多个提供商代码的WebGet。对于每个提供者代码,我需要为其代码存在的所有住院患者返回患者列表,作为录取,就诊或咨询提供者。

应该是:

WHERE (inpatient = 1)
AND (dischargeddate IS NULL)
AND ((attending = 'SMITH') OR (admitting = 'SMITH') OR (consulting = 'SMITH'))

“for”循环不会将条件附加到where子句。我究竟做错了什么??

由于

    [WebGet]
    public IQueryable<vw_patient> GetInpatients(string providercode, string searchtext)
    {
        string[] providers = providercode.Split(new char[] { '|' });

        if (string.IsNullOrEmpty(searchtext))
        {
            var results = (from p in this.CurrentDataSource.vw_patient
                            where p.inpatient.Equals(true)
                            && p.dischargedate.Equals(null)
                            select p);

            foreach (string provider in providers)
            {
                results = results.Where<vw_patient>(e => e.attending.Equals(provider) || e.admitting.Equals(provider) || e.consulting.Contains(provider));
            }

            results.OrderBy(p => p.roomloc).ThenByDescending(p => p.patientname);
            return results;
        }
        else
        {
            var results = (from p in this.CurrentDataSource.vw_patient
                            where p.patientname.StartsWith(searchtext)
                            && p.inpatient.Equals(true)
                            && p.dischargedate.Equals(null)
                            select p);

            foreach (string provider in providers)
            {
                results = results.Where<vw_patient>(e => e.attending.Equals(provider) || e.admitting.Equals(provider) || e.consulting.Contains(provider));
            }

            results.OrderBy(p => p.roomloc).ThenByDescending(p => p.patientname);
            return results;
        }
    }

2 个答案:

答案 0 :(得分:0)

我认为您可能需要将查询结果放入临时存储变量(例如List<vw_patient>),然后将其附加到主列表中。类似的东西: -

就目前而言,你在循环的每次迭代中都覆盖了results变量

List<vw_patient> fullList = new List<vw_patient>();

foreach (string provider in providers){
    results = results.Where<vw_patient>(
        e => e.attending.Equals(provider) || 
             e.admitting.Equals(provider) ||
             e.consulting.Contains(provider)
    );
    fullList.AddRange(result.ToList<vw_patient>());
} 

答案 1 :(得分:0)

取代

foreach (string provider in providers)
{
  results = results.Where<vw_patient>(e => e.attending.Equals(provider) || e.admitting.Equals(provider) || e.consulting.Contains(provider));
}

你可以这样做:

results.Where(e => providers.Contains(e.attending) || providers.Contains(e.admitting) || providers.Contains(e.admitting));