如果使用linq如何使用linq

时间:2015-05-13 11:24:51

标签: c# linq linq-to-sql

这是我的if代码,但所有条件都是和关键字,我如何使用或

if (cbAlis.Checked)
            _search.Where(x => x.faturaturu.ToString().Equals(1));
        if (cbSatis.Checked)
            _search.Where(x => x.faturaturu.ToString().Equals(2));
        if (cbAcik.Checked)
            _search.Where(x => x.faturatipi.Equals("Açık"));
        if (cbKapali.Checked)
            _search.Where(x => x.faturatipi.Equals("Kapalı"));
        if (cbIade.Checked)
            _search.Where(x => x.faturatipi.Equals("İade"));
        if (cbZayiIade.Checked)
            _search.Where(x => x.faturatipi.Equals("Zayi İade"));
        if (cbMuhtelif.Checked)
            _search.Where(x => x.faturatipi.Equals("Muhtelif"));
        if (cbIptal.Checked)
            _search.Where(x => x.faturatipi.Equals("İptal"));
对不起我的英语,对不起。我希望能说出来。

3 个答案:

答案 0 :(得分:0)

你可以这样做:

var urufilters = new List<int>();

if (cbAlis.Checked)
   filters.Add("1");
if (cbSatis.Checked)
   filters.Add("2");

if (filters.Any())
{
   _search = _search.Where(x => filters.Contains(faturaturu));
}

重复你的字符串值。

答案 1 :(得分:0)

由于你似乎有一个用复选框文本搜索的部分,这是我提出的更简单的部分之一:

首先将复选框放在面板中,或类似的东西,以便它们在一个组中。那么代码将变得如此简单:

var itm = panel
  .OfType<CheckBox>()
  .Where(x => x.Checked)
  .Select(x => _search.Where(y => y.faturatipi.Equals(x.Text)));

请注意,使用此方法,前两个仍需要if。

答案 2 :(得分:0)

您可以为每个复选框定义带过滤器的字典:

    public partial class Form1 : Form
    {
        private Dictionary<CheckBox, Func<Model, bool>> _checkboxFilters;
        private IEnumerable<Model> _search;

        public Form1()
        {
            InitializeComponent();

            _search = new List<Model>
            {
                new Model {Property1 = 1, Property2 = "aaa"},
                new Model {Property1 = 2, Property2 = "bbb"},
                new Model {Property1 = 3, Property2 = "Açık"},
                new Model {Property1 = 4, Property2 = "Açık"},
            };

            _checkboxFilters = new Dictionary<CheckBox, Func<Model, bool>>
            {
                {checkBox1, new Func<Model,bool>(x => x.Property1.Equals(1))},
                {checkBox2, new Func<Model,bool>(x => x.Property2.Equals("Açık"))}
            };
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var checkBoxes = this.Controls.OfType<CheckBox>().ToList();
            var checkedCheckBoxes = checkBoxes.Where(n => n.Checked);

            foreach (var checkBox in checkedCheckBoxes)
            {
                if (_checkboxFilters.ContainsKey(checkBox))
                {
                    var filter = _checkboxFilters[checkBox];
                    _search = _search.Where(filter);
                }
            }
        }
    }

    class Model
    {
        public int Property1 { get; set; }
        public string Property2 { get; set; }
    }