c#linq用。创建动态查询

时间:2018-03-04 07:16:29

标签: c# linq

我有5个下拉列表,其中填充了我的数据集列。 这很有效。

var query = ds.Tables["Input"].AsEnumerable().Select
(a => new
{ID = a.Field<string>("ID"),
Element1 = a.Field<string>(comboBoxElement1.SelectedItem.ToString()),
Element2 = a.Field<string>(comboBoxElement2.SelectedItem.ToString()),
Element3 = a.Field<string>(comboBoxElement3.SelectedItem.ToString()),
Element4 = a.Field<string>(comboBoxElement4.SelectedItem.ToString()),
Element5 = a.Field<string>(comboBoxElement5.SelectedItem.ToString())});

但是只有当所有ComboBox都不为空时才有效。 如何动态地仅使用2个选定的框构建查询? 我用StingBuilderif (comboBoxName.SelectedIndex >= 0)语句尝试了它,但我想知道在LINQ中是否还有另一种方法可以做到这一点。

2 个答案:

答案 0 :(得分:0)

我找到了一个简单的解决方案。

从(非空)ComboBoxes:

创建一个列表
List<string> myCollection = new List<string>();

  if (comboBoxElement1.SelectedIndex >= 0)
  {
    myCollection.Add(comboBoxElement1.SelectedItem.ToString());
  }
  if (comboBoxElement2.SelectedIndex >= 0)
  {
    myCollection.Add(comboBoxElement2.SelectedItem.ToString());
  }

从InputTable创建一个DataView:

DataView dv = new DataView(dtInput);

从comboBoxes写入选定的DataColumns到ouputTable:

dtOutput = dv.ToTable(true, myCollection.ToArray());

您可以通过创建如下方法来重构上述内容:

public AddSelected(IList list, params ComboBox[] comboBoxes)
{
    foreach (var comboBox in comboBoxes)
    {
        if (comboBox.SelectedIndex >= 0)
        {
            list.Add(comboBox.SelectedItem.ToString());
        }
    }
}

然后用以下代码调用:

AddSelected(myCollection, comboBoxElement1, comboBoxElement2 /* , ... */ );

答案 1 :(得分:0)

为什么不添加一个只请求selectedIndex!= 0

的where子句 像这样(在WinForm中):

result = Controls.OfType<ComboBox>().Where(cb => cb.SelectedIndex != -1).Aggregate(result, (current, cb) => current + (cb.SelectedItem + ","));

你试试这个:

    var query = ds.Tables["Input"].AsEnumerable().Where(cb => cb.SelectedIndex != -1).Select
(a => new
{ID = a.Field<string>("ID"),
Element1 = a.Field<string>(comboBoxElement1.SelectedItem.ToString()),
Element2 = a.Field<string>(comboBoxElement2.SelectedItem.ToString()),
Element3 = a.Field<string>(comboBoxElement3.SelectedItem.ToString()),
Element4 = a.Field<string>(comboBoxElement4.SelectedItem.ToString()),
Element5 = a.Field<string>(comboBoxElement5.SelectedItem.ToString())});
相关问题