简体   繁体   中英

c# loops taking much times

I am Iterating though datatable through foreach loop. again inside i am using foreach loop inside for iterating through a disctionary.

public void checkforreaptedvals()
{
    foreach (DataRow item in dt.Rows)
    {
        foreach (string str in repeatedvals.Keys)
        {
            if (item["Card Data"].ToString() == str)
            {
                item["Repeated Interval"] = repeatedvals[str];
                if (int.Parse(item["Repeated Interval"].ToString()) > 1)
                {
                    item["Status"] = "Duplicated"; ;
                }
            }
        }
    }   
}

but if my data table row count is more than 10000 then the application will take some time to respond. here dictionay contains how many times one data is repeated ( Dictionary repeatedvals = new Dictionary())

my task here is to check duplicated values in a data table and if duplicated then have to show in another coloumn then interval. that is how many times it is repeated. is there any other ways to iterate through data table.

A dictionary is a collection that is very fast if you lookup by the key. You are enumerating all key-value pairs which is very slow.

This is very fast:

foreach (DataRow row in dt.Rows)
{
    string cardData = row.Field<string>("Card Data");
    bool knownCard = repeatedvals.TryGetValue(cardData, out int repeatCount);
    repeatedvals[cardData] = ++repeatCount;
    row["Repeated Interval"] = repeatCount;
    if (repeatCount > 1)
        row["Status"] = "Duplicated";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM