C# List扩展

1. 洗牌算法(Fisher-Yates)

public static class ListExtensions
{
    private static readonly System.Random Rng = new System.Random();
    
    /// <summary>
    /// 随机打乱指定列表中的元素顺序
    /// </summary>
    /// <typeparam name="T">列表元素的类型</typeparam>
    /// <param name="list">要打乱顺序的列表</param>
    public static void Shuffle<T>(this IList<T> list)
    {
        int listCount = list.Count;
        while (listCount > 1)
        {
            listCount--;
            int randomIndex = Rng.Next(listCount + 1);
            T value = list[randomIndex];
            list[randomIndex] = list[listCount];
            list[listCount] = value;
        }
    }
}

示例代码

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Debug.Log("Original list: " + string.Join(", ", numbers));

numbers.Shuffle();
Debug.Log("Shuffled list: " + string.Join(", ", numbers));

2. 添加数据并获取List Count

public static void AddAndCountListener<T>(this IList<T> list,T data, Action<int> countCallback)
{ 
     list.Add(data);
     int listCount = list.Count;
     countCallback?.Invoke(listCount);
}

示例代码

numbers.AddAndCountListener(1, (count) =>
{
     Debug.Log($"count:{count}");
});

### C# 中 `List<T>` 的 Remove 方法扩展或自定义实现 为了创建一个用于移除列表项的扩展方法,可以利用 C# 提供的扩展方法特性。下面展示了一个名为 `RemoveAllMatching` 的扩展方法的例子,该方法接受谓词作为参数并根据条件删除多个匹配项。 ```csharp using System; using System.Collections.Generic; public static class ListExtensions { /// <summary> /// 移除所有满足指定条件的元素。 /// </summary> /// <typeparam name="T">列表中的类型。</typeparam> /// <param name="list">要操作的列表实例。</param> /// <param name="predicate">用来测试每个元素的函数;返回 true 表示应移除该项。</param> public static void RemoveAllMatching<T>(this List<T> list, Func<T, bool> predicate) { for (int i = list.Count - 1; i >= 0; i--) { if (predicate(list[i])) list.RemoveAt(i); } } } ``` 此代码片段展示了如何遍历整个集合,并通过反向迭代器安全地修改集合大小[^1]。当找到符合条件的对象时,则调用内置的 `RemoveAt()` 函数将其从列表中移除。这种方法允许一次性的批量处理多条记录而无需担心因索引变化引起的问题。 对于更复杂的场景,比如基于二分查找的结果来进行精确位置上的插入或删除操作,也可以参考类似的逻辑结构来设计相应的算法[^2]。 #### 使用示例: 假设有一个整数类型的列表,想要从中移除所有的偶数值: ```csharp var numbers = new List<int> { 1, 2, 3, 4, 5 }; numbers.RemoveAllMatching(n => n % 2 == 0); // 输出结果将是:1, 3, 5 foreach (var num in numbers) { Console.WriteLine(num); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今天喝水了嘛.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值