用c#中的arraylist中的项匹配搜索字符串

本文关键字:搜索 字符串 中的 arraylist | 更新日期: 2023-09-27 17:54:28

我有:

string searchText = System.Console.ReadLine();
ArrayList a = new ArrayList();

我想过滤我的数组列表,我需要找到匹配的项目,即项目的首字母集合

用c#中的arraylist中的项匹配搜索字符串

不要使用ArrayList,它不是强类型的。您应该考虑使用强类型集合,例如List<T>:

string searchText = "text";//Hardcoded for the sake of example
List<string> items = new List<string>();
items.Add("text 1");
items.Add("hello");
items.Add("text 2");
foreach(string item in items)
{
    if(item.StartsWith(searchText))
    {
        System.Diagnostics.Debugger.Break();//Do something...
    }
}

这是你的答案

 ArrayList lx = new ArrayList();
        lx.Add("ABCD");
        lx.Add("ABDM");
        lx.Add("AMFD");
        lx.Add("MXKK");
        ArrayList mx = new ArrayList();
        foreach (string x in lx) {
            if (x.Contains('A')) {
                mx.Add(x);
            }
        }

        foreach (string m in mx) {
            Console.WriteLine(m);
        }
        Console.ReadLine();

如果您使用List和LINQ,解决方案是:

        List<string> newStrings = new List<string>{
          "ABCD","ABDM","AMDF","XMKL"
        };
        List<string> lstA = newStrings.Where((s) => s[0] == 'A').ToList();
        foreach (string m in lstA) {
            Console.WriteLine(m);
        }
        Console.ReadLine();