枚举hashset并从中删除元素

JF *_*ier 5 c# linq hashset

我想通过一个HashSet并对每个元素进行(复杂)检查,这会导致保存元素,从HashSet中删除元素或什么也不做.

由于foreach循环不允许我更改HashSet并且索引不可用,所以我不知道如何执行任务(没有做一些慢的事情,比如先复制HashSet或应用几个LINQ操作,这意味着枚举HashSet比一旦).

有什么建议?

Mat*_*son 7

您只需要使用具有适当谓词函数的RemoveWhere().

你可以产生谓词的副作用,复制被检查的元素(假设你的意思是"保存元素"),如果需要的话.也许这听起来有点hacky,但我觉得它会很好.

这是有效的,因为您的谓词函数将以未定义的顺序与HashSet的每个元素一起呈现,因此您可以决定如何处理每个元素,以及返回true删除它并false保留它.

[编辑]这是一个代码示例.

using System;
using System.Collections.Generic;

namespace Demo
{
    public class Program
    {
        [STAThread]
        private static void Main(string[] args)
        {
            var hashSet = new HashSet<int> {4, 0, 6, -1, 23, -8, 14, 12, -9, 5, 2};
            var itemProcessor = new ItemProcessor();

            hashSet.RemoveWhere(itemProcessor.Process);

            Console.WriteLine("Max = {0}, Min = {1}", itemProcessor.Max, itemProcessor.Min);
            Console.WriteLine("\nHashSet contents:");

            foreach (int number in hashSet)
            {
                Console.WriteLine(number);
            }
        }
    }

    public sealed class ItemProcessor
    {
        private int max = int.MinValue;
        private int min = int.MaxValue;

        // Removes all negative numbers and calculates max and min values.

        public bool Process(int item)
        {
            max = Math.Max(item, max);
            min = Math.Min(item, min);

            return (item < 0);
        }

        public int Max { get { return max; } }
        public int Min { get { return min; } }
    }
}
Run Code Online (Sandbox Code Playgroud)