【问题标题】:Linq into the array then find values in the array and list to comboboxLinq 进入数组,然后在数组中查找值并列出到组合框
【发布时间】:2018-08-13 10:59:49
【问题描述】:

我想将LINQ 查询的结果返回到数组,然后在这个数组中查找列表,例如带有字母"A"。并将列表返回到包含所有字母 "A" 的组合框。

我的 linq 查询:

var collectionName = (
    from row in repos.GetTable<Table_Names>() 
    select row.Name
    ).Distinct().ToArray();

我现在不知道如何搜索数组,以便找到所有包含字母 "A" 的数组。

最终,我想在数组中搜索,而不是向数据库发送查询。这将使组合框中的列表动态缩小。

【问题讨论】:

    标签: c# arrays linq


    【解决方案1】:

    我认为最好获取过滤后的集合,而不是在获取集合后执行搜索。所以我建议你使用像下面这样的Where 子句来只获取过滤的项目:

    string searchString ="A";
    
    from row in repos.GetTable<Table_Names>() 
    where row.Name.Contains(searchString)
    select row.Name;
    

    如果您想获取以给定搜索文本开头的字符串集合,您也可以尝试StartsWith,而不是StartsWith

    【讨论】:

      【解决方案2】:

      如果不想在数据库中过滤,可以使用linq to objects进一步过滤内存中的集合:

      var filtered = collectionName.Where(item => item.Contains("A")).ToArray();
      

      【讨论】:

      • 这里,你放弃了这个:)
      【解决方案3】:

      您可以在 LINQ 查询中使用 SqlMethods.Like。检查下面的代码

      private void comboBox1_TextChanged(object sender, EventArgs e)
          {
              comboBox1.DataSource = getItems(comboBox1.Text);
              comboBox1.DisplayMember = "Name";
              comboBox1.ValueMember = "ID";
          }
          public static List<ComboboxItem> getItems(string text)
          {
              DataClasses1DataContext context = new DataClasses1DataContext();
              try
              {
                  List<ComboboxItem> Ilist = new List<ComboboxItem>();
                  var query =  from x in context.testComboBoxes where SqlMethods.Like(x.name, '%' + text +'%') select x;
                  foreach (var q in query)
                  {
                      ComboboxItem item = new ComboboxItem();
                      item.ID = q.id;
                      item.Name = q.name;
                      Ilist.Add(item);
                  }
                  return Ilist;
              }
              catch (Exception ex)
              {
                  return null;
              }
          }
          public class ComboboxItem
          {
              public object ID { get; set; }
              public string Name { get; set; }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-04
        • 1970-01-01
        • 1970-01-01
        • 2015-09-22
        • 2011-02-13
        • 1970-01-01
        • 2022-12-09
        • 1970-01-01
        相关资源
        最近更新 更多