简体   繁体   中英

c# linq create dynamic query with

I have 5 Dropdown lists which are filled with the columns of my dataset. That works well.

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())});

But that only works if all ComboBoxes are not empty. How can I build the query with only 2 selected Boxes dynamically? I tried it with a StingBuilder and if (comboBoxName.SelectedIndex >= 0) statements, but I'm wondering if there is another method to do that within LINQ.

I found a easy solution.

Create a List from the (not empty) 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());
  }

Create a DataView from the InputTable:

DataView dv = new DataView(dtInput);

Write to the selected DataColumns from comboBoxes to the ouputTable:

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

You can refactor the above by creating a method such as:

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

Then calling with code such as:

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

Why not add a where clause asking for only selectedIndex != 0

like this (in a WinForm):

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

Have you try this:

    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())});

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