1

如果这是一个重复的问题,我很抱歉,我找到了一些类似的问题,但没有一个可以解决我的问题。我有一组具有各种参数的对象,我想使用来自 ComboBoxes 和 TextBoxes 的数据过滤它们。

        var query = from zaj in zajezdy
                    where zaj.Zeme == (String)zemeCombo.SelectedValue
                    && zaj.Oblast == (String)oblastCombo.SelectedValue
                    && zaj.Stredisko == (String)strediskoCombo.SelectedValue
                    && zaj.Doprava.Contains((String)dopravaCombo.SelectedValue)
                    && zaj.Strava.Contains((String)stravaCombo.SelectedValue)
                    && zaj.CenaOd > Int32.Parse(cenaOdText.Text)
                    && zaj.CenaOd < Int32.Parse(cenaDoText.Text)
                    select zaj;

如果正确选择了所有组合,则此代码有效。但是,如果用户留下一些未选择/空的,则查询返回时包含零个对象。如何检测哪些参数为空,以便查询忽略它们?

4

3 回答 3

3

我认为这是规范使用的一个很好的例子。

创建对象,它将代表zajezd规范:

public interface ISpecification<T>
{
    bool IsSatisfiedBy(T value);
}

public class ZajezdSpecification : ISpecification<Zajezd>
{
    private string _zeme;
    private string _oblast;
    private string _stredisko;
    private string _doprava;
    private string _strava;
    private int _cenaOd;
    private int _cenaDo;

    public ZajezdSpecification(string zeme, string oblast, string stredisko, 
        string doprava, string strava, int cenaOd, int cenaDo)
    {
        _zeme = zeme;
        _oblast = oblast;
        _stredisko = stredisko;
        _doprava = doprava;
        _strava = strava;
        _cenaOd = cenaOd;
        _cenaDo = cenaDo;
    }

    public bool IsSatisfiedBy(Zajezd zajezd)
    {
        if (!String.IsNullOrEmpty(_zeme) && zajezd.Zeme != _zeme)
            return false;

        if (!String.IsNullOrEmpty(_oblast) && zajezd.Oblast != _oblast)
            return false;

        // ... verify anything you want

        return _cenaOd < zajezd.CenaOd && zajezd.CenaOd < _cenaDo;
    }
}

并使用 UI 中的值对其进行初始化:

ZajezdSpecification spec = new ZajezdSpecification(
   (string)zemeCombo.SelectedValue,
   (string)oblastCombo.SelectedValue,
   (string)strediskoCombo.SelectedValue,
   ...
   Int32.Parse(cenaDoText.Text)
);

使用此规范过滤您的集合:

var query = from zaj in zajezdy
            where spec.IsSatisfiedBy(zaj)
            select zaj;

PS 尝试在您的代码中使用英文名称。

于 2012-06-09T14:19:47.383 回答
0

首先,尝试为每个 combo\text 引入单独的变量并使用它。使用 String.IsNullOrEmpty 检查字符串。还要尽量避免 Type.Parse() - 改用 Type.TryParse()。样本 :

 var query = from c in dc.Customers select c;
 //filter the result set based on user inputs
 if ( !string.IsNullOrEmpty( countryFilter ) )
   query = query.Where ( c=>c.Country == countryFilter );
 if ( !string.IsNullOrEmpty( cityFilter ) )
   query = query.Where ( c=>c.City == cityFilter );
于 2012-06-09T13:21:08.263 回答
0

您也可以像这样过滤它们,具体取决于参数是否name返回null所有项目,否则仅返回具有指定的元素name

myList.Where(x => name == null || x.Name == name)
      .Where(x => id == null || x.Id == id);
于 2019-02-19T16:51:11.707 回答