user584018 user584018 - 2 months ago 8
C# Question

How to skip list data which already processed?

For demo code, I have a

for
loop which calls a method
LoopData
based on some condition.

In
LoopData
method I am iterating a list
List<Data>
and this method again and again calling on various conditions and every time the whole list
List<Data>
is iterating.

Question is, how to skip those records from the list
List<Data>
which already processed in previous call?

Here's the code,

public class Data
{
public int Id { get; set; }
public int ItemId { get; set; }
}


class Program
{
static void Main(string[] args)
{
List<Data> data = new List<Data>
{
new Data { Id = 1, ItemId = 100 },
new Data { Id = 2, ItemId = 200 },
new Data { Id = 3, ItemId = 300 },

new Data { Id = 4, ItemId = 400 },
new Data { Id = 5, ItemId = 500 }
};

for(int i = 1; i <= 2; i++)
{
if (i == 1)
{
LoopData(data, 100, 300);
}
else
{
LoopData(data, 300, 500);
}
}
}

private static void LoopData(List<Data> data, int startItemId, int endItemId)
{
for(int i = 0; i < data.Count; i++)
{
if(data[i].ItemId >= startItemId && data[i].ItemId <= endItemId)
{
//
}
}
}
}

Answer

Add a property to Data indicating that it is processed or not.

public class Data
{
    public int Id { get; set; }
    public int ItemId { get; set; }
    public bool Processed { get; set; }
}

Set Data.Processed when you have processed the data!

private static void LoopData(List<Data> data, int startItemId, int endItemId)
{
    for(int i = 0; i < data.Count; i++)
    {
        if(!data[i].Processed &&
            data[i].ItemId >= startItemId && 
            data[i].ItemId <= endItemId)
        {
            //            
            data[i].Processed = True; // this data is processed
        }
    }
}
Comments