C#用Array类的FindAll方法和List<T>类的Add方法按关键词在数组中检索元素并输出

目录

一、使用的方法

1. Array.FindAll(T[], Predicate) 方法

(1)定义

(2)示例

2.List类的常用方法

(1)List.Add(T) 方法

(2)List.RemoveAt(Int32) 方法

(3)List.Insert(Int32, T) 方法

(4)List.RemoveAll(Predicate) 方法

(5)List.RemoveRange(Int32, Int32) 方法

(6)示例

二、实例

1.源码

2.生成效果:


一、使用的方法

1. Array.FindAll<T>(T[], Predicate<T>) 方法

        通过使用Array类的FindAll方法来实现根据指定条件在数组中检索元素的功能。

(1)定义

public static T[] FindAll<T> (T[] array, Predicate<T> match);

类型参数
T
数组元素的类型。

参数
array    T[]
要搜索的从零开始的一维 Array。

match    Predicate<T>
Predicate<T>,定义要搜索元素的条件。

返回
T[]
如果找到一个 Array,其中所有元素均与指定谓词定义的条件匹配,则为该数组;否则为一个空 Array。

例外
ArgumentNullException
array 为 null。
- 或 -
match 为 null。

(2)示例

// 创建一个包含 50 个随机数的数组,其值范围为 0 到 1000。
// 然后, FindAll 使用 lambda 表达式为搜索条件,
// 该表达式返回 300 到 600 范围内的值。
namespace _094_1
{
    public class Example
    {
        public static void Main()
        {
            int[] values = GetArray(50, 0, 1000);
            int lowBound = 300;
            int upperBound = 600;
            int[] matchedItems = Array.FindAll(values, x =>
                                             x >= lowBound && x <= upperBound);
            int i = 0;
            foreach (int item in matchedItems)
            {
                Console.Write("{0}  ", item);
                i++;
                if (i % 12 == 0)
                {
                    Console.WriteLine();
                }
            }
            //for (int ctr = 0; ctr < matchedItems.Length; ctr++)
            //{
            //    Console.Write("{0}  ", matchedItems[ctr]);
            //    if ((ctr + 1) % 12 == 0)
            //        Console.WriteLine();
            //}
        }
        /// <summary>
        /// 随机生成整型数组
        /// </summary>
        /// <param name="n">数组元素个数</param>
        /// <param name="lower">范围的下</param>
        /// <param name="upper">范围的上</param>
        /// <returns></returns>
        private static int[] GetArray(int n, int lower, int upper)
        {
            Random rnd = new();
            List<int> list = [];
            for (int ctr = 1; ctr <= n; ctr++)
                list.Add(rnd.Next(lower, upper + 1));

            return [.. list];//等效于return list.ToArray();
        }
    }
}
// 运行结果:
/*
476  417  509  391  461  327  383  500  359  489  495  582
543  313  596  568
 */

2.List<T>类的常用方法

(1)List<T>.Add(T) 方法

         将对象添加到 List<T> 的结尾处。就好像StringBuilder.Append()一样。

public void Add (T item);
参数
item    T
要添加到 List<T> 末尾的对象。 对于引用类型,该值可以为 null。

实现
Add(T)

(2)List<T>.RemoveAt(Int32) 方法

         移除 List<T> 的指定索引处的元素。

public void RemoveAt (int index);

参数
index    Int32
要移除的元素的从零开始的索引。

例外
ArgumentOutOfRangeException
index 小于 0。
或 - index 等于或大于 Count。

(3) List<T>.Insert(Int32, T) 方法

        将元素插入 List<T> 的指定索引处。

public void Insert (int index, T item);

参数
index    Int32
应插入 item 的从零开始的索引。

item    T
要插入的对象。 对于引用类型,该值可以为 null。

实现
Insert(Int32, T)

例外
ArgumentOutOfRangeException
index 小于 0。
- 或 -
index 大于 Count。

(4)List<T>.RemoveAll(Predicate<T>) 方法

         移除与指定的谓词所定义的条件相匹配的所有元素。

public int RemoveAll (Predicate<T> match);

参数
match    Predicate<T>
Predicate<T> 委托,用于定义要移除的元素应满足的条件。

返回
Int32
从 List<T> 中移除的元素数。

例外
ArgumentNullException
match 为 null。

(5)List<T>.RemoveRange(Int32, Int32) 方法

         从 List<T> 中移除一系列元素。

public void RemoveRange (int index, int count);

参数
index    Int32
要移除的元素范围的从零开始的起始索引。

count    Int32
要移除的元素数。

例外
ArgumentOutOfRangeException
index 小于 0。
或 - count 小于 0。
ArgumentException
index 和 count 不表示 List<T> 中元素的有效范围。

(6)示例

namespace _094_2
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            ArgumentNullException.ThrowIfNull(args);
            //添加对象:
            List<int> numbers = [1, 2, 3];
            //删除对象:
            numbers.RemoveAt(1); // 删除索引为1的对象(2)
            //插入对象:
            numbers.Insert(1, 4); // 在索引为1的位置插入对象(4)
            numbers.Add(6);
            numbers.Add(3);
            numbers.Add(6);
            numbers.Add(3);
            numbers.Add(4);
            numbers.Add(5);
            numbers.Add(6);
            //使用RemoveAll方法来删除List<T>中的所有对象:
            numbers.RemoveAll(x => x == 3); // 删除所有值为2的对象

            //使用RemoveRange方法来删除List<T>中指定范围的对象:
            numbers.RemoveRange(1, 3); // 删除索引从1开始的3个对象

            //使用List<T>类的GetEnumerator方法遍历列表中的剩余对象。
            // 先移除一个对象、再插入一个、在添加3个
            numbers.RemoveAt(2);
            numbers.Insert(2, 6);
            numbers.Add(6);
            numbers.Add(78);
            numbers.Add(66);
            // 遍历剩余对象
            for (int i = 0; i < numbers.Count; i++)
            {
                Console.Write("{0}  ",numbers[i]);
            }
            Console.WriteLine();
        }
    }
}
//运行结果:
/*
1  4  6  6  6  78  66

 */

二、实例

        按关键词检索并输出

1.源码

//按关键词检索输出
namespace _094
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private TextBox? textBox2;
        private Label? label1;
        private Label? label2;
        private TextBox? textBox1;
        private string[]? str_array;//定义字符串数组字段

        public Form1()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // textBox1显示
            // 
            textBox2 = new TextBox
            {
                Location = new Point(12, 140),
                Multiline = true,
                Name = "textBox1",
                Size = new Size(290, 69),
                TabIndex = 0
            };
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(39, 95),
                Name = "label1",
                Size = new Size(80, 17),
                TabIndex = 1,
                Text = "输入关键词:"
            };
            // 
            // label2
            // 
            label2 = new Label
            {
                AutoSize = true,
                Location = new Point(135, 19),
                Name = "label2",
                Size = new Size(0, 17),
                TabIndex = 2
            };
            // 
            // textBox2输入
            // 
            textBox1 = new TextBox
            {
                Location = new Point(135, 89),
                Name = "textBox2",
                Size = new Size(125, 33),
                TabIndex = 3
            };
            textBox1.TextChanged += TextBox1_TextChanged;
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 12),
                Name = "groupBox1",
                Size = new Size(290, 122),
                TabIndex = 0,
                TabStop = false,
                Text = "关键词检索"
            };
            groupBox1.Controls.Add(label1);
            groupBox1.Controls.Add(label2);
            groupBox1.Controls.Add(textBox1);
            groupBox1.SuspendLayout();

            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(314, 221);
            Controls.Add(textBox2);
            Controls.Add(groupBox1);
            Name = "Form1";
            Text = "按关键词在数组中检索";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();

            str_array = ["明日科技","C#编程词典","C#范例大全","C#范例宝典"];
            for (int i = 0; i < str_array.Length; i++)//循环输出字符串
            {
                label2.Text += str_array[i] + "\n";
            }
        }
        /// <summary>
        /// 输出检索结果
        /// 使用FindAll方法查找相应字符串
        /// </summary>
        private void TextBox1_TextChanged(object? sender, EventArgs e)
        {
            if (textBox1!.Text != string.Empty)
            {
                string[] str_temp = Array.FindAll
                    (str_array!, (s) => s.Contains(textBox1.Text));
                if (str_temp.Length > 0)
                {
                    textBox2!.Clear();
                    foreach (string s in str_temp)//向控件中添加字符串
                    {
                        textBox2.Text += s + Environment.NewLine;
                    }
                }
                else
                {
                    textBox2!.Clear();
                    textBox2.Text = "没有找到记录";
                }
            }
            else
            {
                textBox2!.Clear();
            }
        }

    }
}

2.生成效果:

 

相关推荐

  1. C#A调用B方法方法更新B控件

    2024-02-06 07:56:02       11 阅读

最近更新

  1. SQL Server设置端口:跨平台指南

    2024-02-06 07:56:02       0 阅读
  2. 指定版本ceph-common安装

    2024-02-06 07:56:02       0 阅读
  3. 中科海讯 C++初级研发工程师笔试题目

    2024-02-06 07:56:02       0 阅读
  4. vue3的常用 Composition API有哪些?

    2024-02-06 07:56:02       1 阅读
  5. Linux系统基础命令行指令——Ubuntu

    2024-02-06 07:56:02       0 阅读
  6. 【Android高级UI】计算不规则图形面积

    2024-02-06 07:56:02       0 阅读
  7. Python库 - PyMC3

    2024-02-06 07:56:02       0 阅读
  8. C语言中关键字

    2024-02-06 07:56:02       0 阅读
  9. ios CCPlistFileWritter.m

    2024-02-06 07:56:02       0 阅读
  10. C#实现Winform程序右下角弹窗消息提示

    2024-02-06 07:56:02       0 阅读

热门阅读

  1. day27回溯

    2024-02-06 07:56:02       39 阅读
  2. iOS面试题

    2024-02-06 07:56:02       34 阅读
  3. zk集群--集群同步

    2024-02-06 07:56:02       28 阅读
  4. 设计模式(创建型模式)原型模式

    2024-02-06 07:56:02       30 阅读
  5. 系统架构设计师-22年-上午答案

    2024-02-06 07:56:02       25 阅读