How to iterate and delete items from hashset in the most efficient way

Well, that’s what I came up with, but I’m curious, this is the most effective way. I need to do this for RAM memory problems.

HashSet<string> hsLinks = new HashSet<string>();
List<string> lstSortList = new List<string>();

// fill hashset with millions of records

while (true)
{
    string srLastitem = "";
    foreach (var item in hsLinks)
    {
        srLastitem = item;
        break;
    }
    lstSortList.Add(srLastitem);
    hsLinks.Remove(srLastitem);
    if (hsLinks.Count == 0)
        break;
}

C # .net 4.5.2 wpf application

+4
source share
2 answers

It seems you are trying to move items from HashSetto List. If this is the case, just move everything once with List.AddRangeand use HashSet.Clearto delete HashSet:

lstSortList.AddRange(hsLinks);
hsLinks.Clear();

If (as Vajura suggested), you are worried about holding 2 copies of links *, you can instead move batches instead of individual elements:

const int batchSize = 1000;
var batch = new string[batchSize];
do
{
    var batchIndex = 0;
    foreach (var link in hsLinks.Take(batchSize))
    {
        batch[batchIndex] = link;
        batchIndex++;
    }

    if (batchIndex < batchSize)
    {
        batch = batch.Take(batchIndex).ToArray();
    }

    hsLinks.ExceptWith(batch);
    lstSortList.AddRange(batch);
} while (hsLinks.Any());

.


* . 4 8 ( 32 64 ). ( .Net) , , ( ).

+5

hsLinks lstSortList ( hsLinks), List<T>.AddRange()

lstSortList.AddRange(hsLinks);
hsLinks.Clear();
+2

All Articles